I am currently working on a nextjs project where i need to use context API and the data coming from context API is completely fine but the typescript shows the error and I don't know what to do.
Error:
Property openDialogFxn does not exist on type Object.
Property state does not exist on type Object.
My Code:
In AlertDialog.tsx
component
export const AlertDialog = ()=> {
const data = useContext(AlertDialogContext);
console.log(data.openDialogFxn) // this line give error but value is accessible
console.log(data.state) // this line give error but value is accessible
}
In AlertContext.tsx
:
export const AlertDialogContext = createContext<null | Object>(null);
In AlertDialogState.tsx
:
export function AlertDialogProvider({ children }: any) {
const [currentValue, setCurrentValue] = useState<boolean>(false);
const openDialogFxn = () => {
setCurrentValue(true);
}
const currentState = {
state: currentValue,
openDialogFxn
}
return (
<AlertDialogContext.Provider value={currentState}>
{children}
</AlertDialogContext.Provider>
);
}
I just Want to know that why i am getting the typescript error?
The type you have passed in null | Object
throws an error because neither of properties you are accessing (state, openDialogFxn) exist on the type definition for Object.
You can solve this by defining a type:
type TAlertDialogContext = {
state: boolean;
openDialogFn: () => void;
};
And passing that to your call to createContext:
const AlertDialogContext = createContext<TAlertDialogContext | null>(null);
Here's a Code Sandbox with the updated code.
Hope this helps!