How do I store some values in the broswer scope from a react component?

Viewed 58

I don't know if I have used the right terminology, but this is what I am trying to do. I am fetching some header details from one of my API's which includes the bearer token, and other details. These values will be used by most of the other react components. Is there a way to store it globally without using Redux or passing the data to all the individual components?

Below is a code snippet which gets the value from the state of the location of a React component. I need to store these values globally without using redux.

      if (response.httpStatus === 200) {
        setIsLoggedIn(true);
        //setIsAdmin(response.user.isAdmin!);
        setEmailAddress(inputEmailAddress);
        history.push('/console',{
                                token:response.token,
                                companyID: response.user.companyID, 
                                firstName: response.user.firstName, 
                                lastName: response.user.lastName,
                                emailAddress: response.user.emailAddress 
                                } //<--- I also need to store this object globally in the browsers scope so that they can be used by all other react components. 
                    );

      }

My question might sound silly and might lack the right terminologies. My work is mostly in the API and the database. I don't have much expertise or knowledge using react.

3 Answers

You can use a pattern like this:

Storing data into some parent state and using React.createContext and React.useContext.

For more complex applications other than a few components, a really recommend you moving to Redux. Use @reduxjs/toolkit 'cause it makes Redux code less verbose and it's the official recommendation to write Redux code for most applications.

function mockApi() {
  return new Promise((resolve,reject) => {
    setTimeout(() => resolve("API DATA"), 1000);
  });
}

const GlobalContext = React.createContext(null);

function App() {

  console.log("Rendering App...");

  const [apiData,setApiData] = React.useState(null);
  
  React.useEffect(() => {
    mockApi().then((data) => {
      setApiData(data);
    });
  },[]);

  return(
    <GlobalContext.Provider value={apiData}>
      <SomeComponent/>
    </GlobalContext.Provider>
  );
}

function SomeComponent() {

  const apiData = React.useContext(GlobalContext);

  return(
    apiData? 
      <div>SomeComponent: {apiData}</div>
    : <div>SomeComponent: Loading data...</div>
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

Apologies for not mentioning that I was using Ionic framework. I used the storage capacitor to store the values globally.

Related