Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I am using context API in nextjs and its completely working fine but the typescript give the error

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading