Skip to content Skip to sidebar Skip to footer

How To Change React Context Programmatically?

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'; e

Solution 1:

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

classAppextendsReact.Component {
   state = {
      isAuth: false;
   }
   componentDidMount() {
      APIcall().then((res) => { this.setState({isAuth: res}) // update isAuth })
   }
   render() {
       <LoggedUserContext.Providervalue={this.state.isAuth}><Child /></LoggedUserContext.Provider>
   }
}

The section about dynamic context explains it

Solution 2:

Wrap your consuming component in a provider component:

importReactfrom'react';

constSERVER_URL = 'http://some_url.com';

constLoggedUserContext = React.createContext();

classAppextendsReact.Component {
    state = {
        user: null,
        id: 123
    }
    componentDidMount() {
        axios.get(`${SERVER_URL}/users/${this.state.id}`).then(response => { 
            const user = response.data.user; // I can only guess herethis.setState({user});
        });
    }
    render() {
        return (
            <LoggedUserContext.Providervalue={this.state.user}><LoggedUserContext.Consumer>
                    {user => (
                        (user.name) ? user.name : 'Choose a user or create one';
                    )}
                </LoggedUserContext.Consumer></LoggedUserContext.Provider>
        );
    }
}

I gave a complete example to make it even clearer (untested). See the docs for an example with better component composition.

Post a Comment for "How To Change React Context Programmatically?"