Categories
React Answers

Hoe to Update the Context Value in Provider from the Consumer?

Spread the love

Sometimes, we want to update the context value in a provider from the consumer of the React Context API.

In this article, we’ll look at how to to update the context value in a provider from the consumer of the React Context API.

Update the Context Value in Provider from the Consumer

We can update the context value from the provider if we pass in the function into the context.

For instance, we can write:

const MyContext = React.createContext({});

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: ""
    };
  }

  onChange(e){
    const name = e.target.value;
    this.setState({
      name
    });
    this.props.context.updateValue('name', name);
  }

  render() {
    return (
       <React.Fragment>
         <input onChange={this.onChange} />
       </React.Fragment>
    )
  }
}

const withContext = (Component) => {
  return (props) => {
    <MyContext.Consumer>
      {(context) => {
           return <Component {...props} context={context} />
      }}
    </MyContext.Consumer>
  }
}

Child = withContext(Child)

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "bar",
    };
  }

  updateValue = (key, val) => {
    this.setState({[key]: val});
  }

  render() {
    return (
      <MyContext.Provider value={{ state: this.state, updateValue: this.updateValue }}>
        <Child />
      </MyContext.Provider>
    )
  }
}

We create the context and pass the value from the Parent to the components in the context.

The object has the state and the updateValue function.

We then get the updateValue method from the props.context property, which is what we have.

Then we set the name by calling the updateValue method to set the name state of the Parent .

We’ve to remember to add the MyContext.Consumer to whatever component is consuming the context.

To do that, we created the withContext higher-order component to wrap any component with the context consumer.

Conclusion

We can update the context value from the provider if we pass in the function into the context.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *