Home > database >  Cannot invoke an object which is possibly 'null' context
Cannot invoke an object which is possibly 'null' context

Time:04-06

why I get this ts error:

Cannot invoke an object which is possibly 'null'.

Context.tsx

import React, { createContext, useState } from 'react';

type ForgotPasswordProviderProps = {
  children: React.ReactNode;
}

export type Email = {
  email: string | null;
  setEmail: React.Dispatch<React.SetStateAction<string>> | null;
}

export const ForgotPasswordContext = createContext<Email | null>(null);

export const ForgotPasswordContextProvider = ({
  children
}: ForgotPasswordProviderProps) => {
  const [email, setEmail] = useState('');
  return <ForgotPasswordContext.Provider value={{email, setEmail}}>{children}</ForgotPasswordContext.Provider>
}

ForgotPassword.tsx

  const handleChangeEmail = (e: string) => (emailContext && emailContext.setEmail('asas');

this error comes on line: emailContext.setEmail

How can I solve this issue ?

CodePudding user response:

Your context defines this type:

export type Email = {
  email: string | null;
  setEmail: React.Dispatch<React.SetStateAction<string>> | null;
}

Which says that the setEmail property could be a state setter function or it could be null.

Which means when you execute this:

emailContext && emailContext.setEmail('asas')

Then emailContext.setEmail might be null.

To fix it you need to verify that the property has a value before you use it. You can use the optional chaining operator ?. to safely drill in here:

emailContext?.setEmail?.('asas')
  • Related