Home > Net >  React Context State Not Updating
React Context State Not Updating

Time:05-15

My Context:

type Props = {
  children: React.ReactNode;
};

interface Context {
  postIsDraft: boolean;
  setPostIsDraft: Dispatch<SetStateAction<boolean>>;
}

const initialContext: Context = {
  postIsDraft: false,
  setPostIsDraft: (): void => {},
};

const EditPostContext = createContext<Context>(initialContext);

const EditPostContextProvider = ({ children }: Props) => {
  const [postIsDraft, setPostIsDraft] = useState<boolean>(
    initialContext.postIsDraft
  );
  return (
    <EditPostContext.Provider
      value={{
        postIsDraft,
        setPostIsDraft,
      }}
    >
      {children}
    </EditPostContext.Provider>
  );
};

export { EditPostContext, EditPostContextProvider };

I set postIsDraft in the parent:

export const ParentComponent = () => {
  { setPostIsDraft } = useContext(EditPostContext);

  // some code

  const updatePostStatus = (postStatus: boolean) => {
    setPostIsDraft(postStatus);
  }

  // some code
  
  return(
    <EditPostContextProvider>
      <ChildComponent />
    </EditPostContextProvider>
  )
}

Then I need to read the value in the child component:

  const { postIsDraft } = useContext(EditPostContext);

Only just starting use context, just not sure what I've done wrong. When I try and read the value from context in the child component, I'm only getting back the initial value, not the set value in the parent component.

CodePudding user response:

Your ParentComponent should be wrapped inside provider so as to use it's value:

    <EditPostContextProvider>
      <ParentComponent />
    </EditPostContextProvider>

Generally we can put the provider in index.js file, and wrap <app /> in it

  • Related