How to change React context programmatically?

kace91 picture kace91 · Apr 3, 2018 · Viewed 21.8k times · Source

I'm trying to use the new React context to hold data about the logged-in user.

To do that, I create a context in a file called LoggedUserContext.js:

import React from 'react';


export const LoggedUserContext = React.createContext(
  );

And sure enough, now I can get access to said context in other components using consumers, as I do here for example:

  <LoggedUserContext.Consumer>
       {user => (
       (LoggedUserContext.name) ? LoggedUserContext.name : 'Choose a user or create one';
       )}
   </LoggedUserContext.Consumer>

But obviously, for this system to be useful I need to modify my context after login, so it can hold the user's data. I'm making a call to a REST API using axios, and I need to assign the retrieved data to my context:

axios.get(`${SERVER_URL}/users/${this.state.id}`).then(response => { /*What should I do here?*/});

I see no way to do that in React's documentation, but they even mention that holding info of a logged in user is one of the use cases they had in mind for contexts:

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language. For example, in the code below we manually thread through a “theme” prop in order to style the Button component:

So how can I do it?

Answer

Shubham Khatri picture Shubham Khatri · Apr 3, 2018

In order to use Context, you need a Provider which takes a value, and that value could come from the state of the component and be updated

for instance

class App extends React.Component {
   state = {
      isAuth: false;
   }
   componentDidMount() {
      APIcall().then((res) => { this.setState({isAuth: res}) // update isAuth })
   }
   render() {
       <LoggedUserContext.Provider value={this.state.isAuth}>
           <Child />
       </LoggedUserContext.Provider>
   }
}

The section about dynamic context explains it