'Context API using the initial value not the one set in UseState
I just started using typescript with react and tried to deal with ContextAPI with the typescript. So Far I've set a context and tried to use a provider inside my app.tsx. My context file is looking like this:
import { createContext, ReactNode, useState } from "react";
type props = {
children: ReactNode
}
type GlobalContextType = {
currentValue: number;
setCurrentValue: (value: number) => void;
}
const INITIAL_VALUE = {
currentValue: 1,
setCurrentValue: () => {},
}
export const GlobalContext = createContext<GlobalContextType>(INITIAL_VALUE);
export const GlobalProvider = ({ children }: props) => {
const [currentValue, setCurrentValue] = useState(3);
return(
<GlobalContext.Provider value={{ currentValue, setCurrentValue }}>
{ children }
</GlobalContext.Provider>
)
}
while my app.tsx file is looking like this:
import './App.css';
import { useContext } from 'react';
import { GlobalContext, GlobalProvider } from './ContextAPI/GlobalContext';
function App() {
const { currentValue, setCurrentValue } = useContext(GlobalContext);
return (
<GlobalProvider>
<h1>{ currentValue }</h1>
<button onClick={() => setCurrentValue(currentValue + 1)}>Increment</button>
</GlobalProvider>
);
}
export default App;
There are few things that didn't work as I expected. First: when I go to my localhost page it displays the inital value, which is 1, not the one that I set using useState(3). Second: When I click the button, it doesn't update the value.
I imagine that I'm always using the initial state value and not the one that I'm trying to set inside the provider.
Solution 1:[1]
Try to set the function increment in the context API then call it in the app right just after onClick event
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Elyes Ben khoud |