I want to store a global variable that's mutable and accessible in all files of my React.js project, including index.js where the ApolloClient is rendered. At first, I thought to create a class but I wasn't sure how to implement that and save the state of the variable across multiple pages. Upon doing research, I discovered the use of context, but I don't quite understand the documentation. Please advise what the best practice would be. Thank you.
Edit:
I attempted to import a global variable, but that isn't mutable. I also attempted making a class that extends React.Component, to access functionalities such as useState()
but a class of that nature must return a component if I understand correctly. Upon reading into Context more, I'm starting to gain a little more understanding, but I still don't fully understand how to implement it.
I created a file AuthHandler:
import { createContext } from 'react';
export var AuthData = {
id: createContext(0),
auth: createContext("")
}
I want to mutate that data in a component function, and then access it in index.js. How would I go about doing that?
Your use case here will be consumed by something outside of React (an Apollo Link), so Context does not make any sense here - Context would make a value available to children in the React tree, but your link is not a child in a React Tree.
Instead you can just export an object and modify that object (you probably cannot reassign it depending on how you import/export it, but you can always modify it).
// index.js
export const globalData = {
auth: null
}
// anywhere else
import { globalData } from './index.js'
globalData.auth = "foo"
That said, you can only work with global data like this if you are not using SSR. If you are using SSR (e.g. in a Client Component in Next.js), you'd need to find another way of doing that.
In that case, you could use Apollo CLient's defaultContext
.