//App.tsx
import { createContext, useState } from "react";
import { defaultFormData } from "./components/Context";
const theme = createTheme({
typography: {
fontFamily: "Manrope, sans-serif",
},
});
export const FormStateContext = createContext({});
function App() {
const [formData, setFormData] = useState(defaultFormData);
return (
<ThemeProvider theme={theme}>
<FormStateContext.Provider value={{ formData, setFormData }}>
//step.tsx
import { FormStateContext } from "../../App";
import { useContext } from "react";
export function step() {
const {formData, setFormData} = useContext(FormStateContext);
Every time I try to destructure the object in any way I get the error which says that the attributes don’t exist in the type {}
.
Edit: sorry, i’ve forgotten to include the rest of the code, hope it’ll help somehow, if anyone wants to view the entirety of this trash pile here’s the github link
2
Answers
Check the default value that you are using as createContext parameter it shouldn’t be null or undefined.
When you call
createContext({})
without any type anotation, typescript cannot do anything but infer the type{}
to the context valueWhat you want to do instead is to assign the type
In order to do so you should create the context this way:
We allow
null
to avoid having to pass an actual default value. It comes handy with complex context. Don’t worry we get rid of it later onWith this you still can’t destructure since the context can be
null
To go around that create a custom hook that throws if the context is nullish
This way
useMyContext
always returns the typeContextValue
You can new destructure