I need to share global variables through multiple components, and it seems that my context is not working as expected.
I declared in a seperated file globalContext.tsx
:
export type GlobalContent = {
entities: entity[]
setEntities:(c: entity[]) => void,
pallets: string[],
setPallets:(c: string[]) => void,
}
export const GlobalContext = createContext<GlobalContent>({
entities: [], // set a default value
setEntities: () => {},
pallets: [],
setPallets: () => {}
})
Then, initialize and my values in my App.tsx, then wrapping all my tree in the Provider :
function App() {
// Init global variables, accessible everywhere using useContext hook
const [entities, setEntities] = useState<entity[]>([])
const [pallets, setPallets] = useState<string[]>(["hello"])
let defaultGlobals: GlobalContent = { entities, setEntities, pallets, setPallets }
return (
<GlobalContext.Provider value={defaultGlobals}>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/picking" element={<Picking/>}/>
<Route path="/control" element={<Control/>}/>
<Route path="/place" element={<Place/>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>
</BrowserRouter>
</GlobalContext.Provider>
)
}
So, there should be it. Within my components (let's say <Picking/> for example), I can get find back my default values by using the following :
const { entities, setEntities, pallets, setPallets } = useContext(GlobalContext)
But when I grab this data in another component (<Control/> or <Place/>) using :
const { entities, setEntities, pallets, setPallets } = useContext(GlobalContext)
I keep getting the default value (a.k.a. the "defaultGlobals", with ["hello"] array).
I tried changing my entities
or pallets
content using the corresponding setters, and the variables extracted from the useContext are definitively independant from a component to another.
Still getting default values at first.
Seems something is breaking the context or I am doing something wrong here. Any help ?
Here's a link to a running codesandbox.
Example consumer:
export default function Home() {
const { entities, setEntities, pallets, setPallets } = useContext(
GlobalContext
);
return (
<div>
<a href="/other">Move to Other</a>
<h1>Home component</h1>
<button onClick={() => setPallets([...pallets, "newPallet"])}>
Add pallet
</button>
{pallets.map((pallet) => {
return <p>{pallet}</p>;
})}
</div>
);
}