Home > OS >  Update React context to use in separate functions?
Update React context to use in separate functions?

Time:01-02

I currently have a context:

const statusContext = React.createContext({
    Status: 'login',
    setStatus: () => {
          Status:
            Status === "login"
              ? "signin"
              : "login"
              
    },
});

I want to use Status in several separate unnested functions, and I want to be able to change the value of Status in each as well. I read in the guide how to do this from a nested component; however, that is not my case here. Was hoping for some guidance, not sure if this is the right way to do it.

CodePudding user response:

In react everything works in a tree. So if you want to use the context api you need to have nested components. So your only option is to make a wrapper component and move it to the top of your app. Then you can use the context api something like this:

const StatusContext = React.createContext()

const StatusProvider = ({children}) => {
  const [status, setStatus] = useState('login')

  return <StatusContext.Provider value={{status, setStatus}}>{children}</StatusContext.Provider>
}

const StatusDisplay = () => {
  const {status} = useContext(StatusContext)
  return (
    <div>{status}</div>
  )
}

const StatusSwitcher = () => {
  const {setStatus} = useContext(StatusContext)
  return <button onClick={() => setStatus('logged in')}>Login</button>
}

const App = () => {
  return (
    <StatusProvider>
      <StatusDisplay />
      <StatusSwitcher />
    </StatusProvider>
  );
};

CodePudding user response:

You can pass state into the context and update from any nested component.

import { useState, useContext, createContext } from "react";
const UserContext = createContext("Unknown");

export default function Application() {
  const [userName, setUserName] = useState("paul");
  return (
    <UserContext.Provider value={{ userName, setUserName }}>
      <Layout>Main content</Layout>
    </UserContext.Provider>
  );
}
function Layout({ children }) {
  return (
    <div>
      <Header />
      <main>{children}</main>
    </div>
  );
}
function Header() {
  return (
    <header>
      <UserInfo />
    </header>
  );
}
function UserInfo() {
  const { userName, setUserName } = useContext(UserContext);
  return (
    <>
      <button onClick={() => setUserName("michael")}>
        change Name in context
      </button>
      <div>{userName}</div>
    </>
  );
}

working example: https://codesandbox.io/s/busy-euler-66gel?file=/src/App.js:0-790

  • Related