I am trying to create context-api to store userdetails and tokens in react using typescript, As I am new to typescript I cannot understand the following errors please help. .................................................................................................
Code:
import { createContext, useReducer } from "react";
type Action =
| { type: "USER_LOGIN_REQUEST"; }
| { type: "USER_LOGIN_SUCCESS";payload: string}
| { type: "USER_LOGIN_FAIL"; payload: string };
interface UserAuthProviderProps {
children: React.ReactNode;
}
type AppState = typeof INITIAL_STATE;
const INITIAL_STATE = {
userInfo: localStorage.getItem("userInfo")
? localStorage.getItem("userInfo")
: null,
};
const userLoginreducer = (state: AppState, action: Action) => {
switch (action.type) {
case "USER_LOGIN_REQUEST":
return { loading: true };
case "USER_LOGIN_SUCCESS":
return { loading: false, success: true, userInfo: action.payload };
case "USER_LOGIN_FAIL":
return { loading: false, error: action.payload };
default:
return state
}
};
const UserAuthContext = createContext<{
state: AppState;
dispatch: React.Dispatch<Action>;
}>(INITIAL_STATE);
function UserAuthProvider({ children }: UserAuthProviderProps) {
const [state, dispatch] = useReducer(userLoginreducer, INITIAL_STATE);
return (
<UserAuthContext.Provider value={{ state, dispatch }}>
{children}
</UserAuthContext.Provider>
);
}
export { UserAuthContext, UserAuthProvider };
Errors
Type '{ userInfo: string | null; }' is missing the following properties from type '{ state:
{ userInfo: string | null; }; dispatch: Dispatch<Action>; }': state, dispatch
Argument of type '{ userInfo: string | null; }' is not assignable to parameter of type
'never'.
CodePudding user response:
You context should have type AppState
:
type AppState = {
userInfo: string | null,
success: boolean,
error: string,
};
const INITIAL_STATE: AppState = {
userInfo: localStorage.getItem('userInfo')
? localStorage.getItem('userInfo')
: null,
success: true,
error: '',
};
const UserAuthContext = createContext<AppState>(INITIAL_STATE);