Home > Back-end >  Having difficulties in assinging Type for useContext in TypeScript
Having difficulties in assinging Type for useContext in TypeScript

Time:08-22

I am using useContext for authentication purposes and my code is of below


type userSignup = {
name: string;
email: string;
password: string;
signup() => void;
}

export const AuthContext = createContext<userSignup|null>(null);

export const AuthProvider = ({children}) =>{
const signup = async (name,email,password) => {

const DTO ={name:name, email:email:, password:password}


const response = await fetch('url',DTO);
const data = await response.json();

setToken(data);


}
}

return (
<AuthContext.Provider value={{signup}}> {children} </AuthContext.Provider>
);

The issue is an error appears telling me that type (name: string, email: string,password: string, signup() => Promise) is not assignable to type userSignup.

I can overcome this by changing the

export const AuthContext = createContext<any|null>(null);

but I don't think using any is a good approach.

Could someone please suggest a better solution for this? Thank you in advance

//UPDATE 1

As David Alvarez suggested. I have changed the type userSignUp into:

type userSignUp ={ 
name: string;
email: string;
password: password;
signup: () => Promise<void>;
}

Now the error message says: Type'(name:any, email:any, password:any) => Promise<void>' is not assignable to type '()=> Promise<void>'

CodePudding user response:

It is in the compiler error :) signup() => Promise is not assignable to signup() => void.

According to the docs:

RETURN TYPE: A Promise which will be resolved with the value returned by the async function, or rejected with an exception thrown from, or uncaught within, the async function.

Change your type from

type userSignup = {
  name: string;
  email: string;
  password: string;
  signup() => void;
}

to

type userSignup = (name: string, email: string, password: string) => Promise<void>;

And it should work.

  • Related