0

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.

0

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I'll accept once the timer is up, I think that's done it. Is there a preferred way of handling multiple providers in this way? The index.js file could get quite busy with multiple nested providers I'm guessing?
Wrapper hell is sometimes a issue with readability in react, but other than that, I don't think there's anything wrong with mutiple providers/wrappers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.