skip to Main Content
//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


  1. Check the default value that you are using as createContext parameter it shouldn’t be null or undefined.

    const SomeContext = createContext(defaultValue)
    
    Login or Signup to reply.
  2. When you call createContext({}) without any type anotation, typescript cannot do anything but infer the type {} to the context value

    What you want to do instead is to assign the type

    type ContextValue = {formData: MyFormData, setFormData: React.Dispatch<React.SetStateAction<MyFormData>>}
    

    In order to do so you should create the context this way:

    const Context = createContext<null | ContextValue>(null);
    

    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 on

    With 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

    const useMyContext = () => {
       const ctx = useContext(Context) 
       if(!ctx) throw new Error('context not found') 
       return ctx
    } 
    

    This way useMyContext always returns the type ContextValue

    You can new destructure

    const {formData, setFormData} = useMyContext() 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search