I'm using Context API for the first time and I'm having some difficulties to understand how to update context in lifecycle methods. I had a look at the official doc and this answer which made sense but didn't help me much to find a solution.
I have 2 components for now: one parent and one child.
In the parent, I'm using an axios get() request in componentDidMount() to fetch data.
The child uses context to render elements so it needs the updated context once the request is complete.
My main issue is I can't find out where to update the provider state once the axios response is received. Ideally I'd like to assign the axios response to the provider state but I can't figure out how to access the context from there.
I made it "work" by assigning the axios response to the parent state then by updating the context provider state with it through a handler from my Provider and called this handler in render() under my Consumer since it's the only place I believe I have access to the context:
class ParentComponent extends Component {
render() {
return (
<MyContext.Consumer>
{(context) => {
if(axiosSuccess) {context.updateContextState(parentState);}
return (
<ChildComponent/>
)
}}
</MyContext.Consumer>
);
}
}
However I know it's not the right implementation since updating in render() is an anti-pattern.
What is the best way to update provider state in lifecycle methods?