Maybe I'm missing something, but I can't find a solution for that.
I have a React component and want to run some periodic background job (setInterval) This job use some information of the components state and should also be able to change that.
My component:
export default function Form() {
const [state, setState] = useState<IState>(initialState);
useEffect(() => {
//init component and other stuff
// trigger background Task
setInterval(backgroundJob, 10000);
}, []);
function backgroundJob(){
state.xxx
}
function handleButtonClick(){
state.xxx = state.xxx + 1;
setState({
...state,
});
}
}
The main problem is, the backgroundJob Function is able to access the state, but it's only the initalState
. If the state
is updated, (e.g. on a button click via the handleButtonClick()
function), the next Interval tick still has old values in the state
Do I misunderstood some basic concept here?