I have a variable "second", which needs to be updated every second. and it was used by multiple components so i placed it in context.
Only for the first time i see correct value and from the next iteration it is coming as undefined. any advice please
Output:
state is {second: 43, error: null}
state is {second: undefined, error: null}
and i'm using setInterval
inside useEffect
to update the variable every second
Code
import React, { useReducer, useEffect } from "react";
export const SecContext = React.createContext();
const initialState = {
second: new Date().getSeconds(),
error: null,
};
const reducer = (state, action) => {
switch (action.type) {
case "UPDATE_SECOND":
return {
...state,
second: action.second,
};
default:
throw new Error();
}
};
export const SecContextProvider = (props) => {
const [state, dispatch] = useReducer(reducer, initialState);
const updateSecond = () => {
let second = new Date().getSeconds();
console.log("state is ", state);
dispatch({
type: "UPDATE_SECOND",
payload: second,
});
};
useEffect(() => {
const timeoutId = setInterval(() => {
updateSecond();
}, 1000);
return function cleanup() {
clearInterval(timeoutId);
};
}, [updateSecond]);
return (
<SecContext.Provider value={[state, dispatch]}>
{props.children}
</SecContext.Provider>
);
};
export default SecContextProvider;
Sorry for writing this answer, but I am not able to add a new comment.
A minor issue I saw
return {
...state,
second: action.second, // you refer to action.second, which is undefined, you need action.payload here
};