Home > Net >  "Expected 1 arguments, but got 2" when passing a useState function in TypeScript
"Expected 1 arguments, but got 2" when passing a useState function in TypeScript

Time:01-26

I have a component which passes a useState setter to a utility function:

export interface IData {
  editable: string[];
  favourited: string[];
}

const [data, setData] = useState<IData | undefined>(undefined)

useEffect(() => {
    if (status === "authenticated") {
      fetchUserDoc(session?.user?.uid, setData);
    }
  }, [status]);

The utility function gets a document from Firestore and passes the document data to the setter. If the document doesn't exist, it creates the document and then calls itself to redo the process.

export interface IFetchDocProps {
  uid: string;
  setData: Dispatch<SetStateAction<DocumentData>>;
}

export default async function fetchUserDoc({
  uid,
  setData,
}: IFetchDocProps) {
  const docRef = doc(db, "users", uid);
  const docSnap = await getDoc(docRef);

  if (docSnap.exists()) {
    let data = docSnap.data();
    setData(data);
  } else {
    await setDoc(doc(db, "users", uid), {
      editable: [],
      favourited: [],
    });
    fetchUserDoc(uid, setData);
  }
}

When fetchUserDoc(uid, setData) is called it gives the error Expected 1 arguments, but got 2.ts(2554).

Any pointers? I think I may have confused the interfaces somehow.

CodePudding user response:

The function fetchUserDoc only has 1 parameter which is

{
  uid,
  setData,
}: IFetchDocProps

is is an interface with to fields/attributes inside but in therms of function parameter it is only one.

And when you are calling the function you are passing 2 parameters:

fetchUserDoc(uid, setData);

uid -> Pram1 setData -> Para2

To fix this you will have to instantiate one object with to attributes inside and pass it as a single parameter:

//pseudocode!!
//Initialize argument object passing two fields it has 
let param = new IFetchDocProps( uid, setData )
// call the function passing a single parameter
fetchUserDoc( param )

Those are Pseudocodes just get the idea...

CodePudding user response:

Pretty simple, your function is expecting a single argument as an object, so you should call it like;

fetchUserDoc({uid, setData});
  •  Tags:  
  • Related