'React Redux state is not being updated when using useSelector inside useEffect
I'm new to react and when I'm updating my state in redux, I'm no able to see my state updated in my component inside a setInterval
, despite the state in redux is updated correctly (according to a chrome redux plugin); in the useEffect
in my App component, when console.log(state)
, I only see the same default state {number:0}
all the time despite that there is a setInterval
running and updating the state all the time, I'm using the redux plugin for chrome and the state in redux is being updated, but when trying to query the state using the useSelector
in my useState, I always get the same state {number:0}
, so I don't know if there's a fail in the useSelector
, or there is something that the setInterval
is not allowing me to see the current state that I can see in the redux chrome plugin. Do you know what could be wrong?
I have the following code:
import {useSelector, useDispatch} from 'react-redux'
import { useEffect } from 'react';
import allActions from './store/actions/allActions'
const App = () => {
const state = useSelector(state => state.numberReducer)
const dispatch = useDispatch();
useEffect(() => {
setInterval(() => {
console.log(state)
let currentTimeAsTimestamp = new Date().getTime() + 6*60000;
if(state.number === 0) {
const newNumber = state.number +2;
dispatch(allActions.numberActions.updateNumber("UPDATE_NUMBER", newNumber));
}else {
const newNumber = state.number +1;
dispatch(allActions.numberActions.updateNumber("UPDATE_NUMBER", newNumber));
}
}, 1000)
},[])
return(
//some stuff
)
}
Here are my actions:
import numberActions from "./numberActions";
const allActions = {
numberActions,
};
export default allActions;
Here is my updateNumber
action:
const updateNumber = (type, newNumber) => {
return {
type: "UPDATE_NUMBER",
newNumber: newNumber,
};
};
export default {
updateNumber
};
And here is my reducer:
import * as actionTypes from '../actions/actionTypes';
export const defaultState = {
number: 0,
}
const numberReducer= (state = defaultState, action) => {
switch (action.type) {
case "UPDATE_NUMBER":
console.log("IN UPDATE NUMBER")
console.log(action);
return {...state,
number: action.newNumber
}
default:
return state;
}
}
export default numberReducer;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|