1

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?

Fred
  • 639
  • 4
  • 14
  • 27
  • Please see https://stackoverflow.com/questions/49809884/access-react-context-outside-of-render-function for your answer. – Mr.Drew Aug 24 '21 at 15:01

1 Answers1

-1

Using context not differs much from usual state/props/redux usage. Pass handlers (beside values) from context the same way as from parent (by props). Move entire fetch to context (component) or at least pass handler to update state. Look at toggleTheme in docs.

xadm
  • 8,219
  • 3
  • 14
  • 25