'React Context State Not Updating
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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Enfield li |
