Categories
JavaScript Answers

How to update the Context value in a Provider from the Consumer with React?

Spread the love

To update the Context value in a Provider from the Consumer with React, we pass the state setter function from the provider so it can be retrieved by the consumer.

For instance, we create the authContext.js file with

import { createContext } from "react";

const authContext = createContext({
  authenticated: false,
  setAuthenticated: (auth) => {}
});

export default authContext;

We call createContext to create the context with an object with some data we want to share.

Next, in login.js, we write

import React, { useContext } from "react";
import authContext from "./authContext";

export default () => {
  const { setAuthenticated } = useContext(authContext);
  const handleLogin = () => setAuthenticated(true);
  const handleLogout = () => setAuthenticated(false);

  return (
    <React.Fragment>
      <button onClick={handleLogin}>login</button>
      <button onClick={handleLogout}>logout</button>
    </React.Fragment>
  );
};

to call useContext to get the authContext.

And then we call the setAuthenticated function to set the value of authenticated.

Finally, we write

import ReactDOM from "react-dom";
import React, { useState } from "react";

import authContext from "./authContext";
import Login from "./Login";

const App = () => {
  const [authenticated, setAuthenticated] = useState(false);

  return (
    <authContext.Provider value={{ authenticated, setAuthenticated }}>
      <div> user is {`${authenticated ? "" : "not"} authenticated`} </div>
      <Login />
    </authContext.Provider>
  );
};

ReactDOM.render(<App />, document.getElementById("container"));

in index.js to call useState to create the authenticated state.

We pass authenticated and setAuthenticated into the context by setting the value prop of authContext.Provider to an object with authenticated and setAuthenticated.

As a result, we call call it in login.js since we pass the values in the provider.

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 *