I'm working on an application which uses react for the front-end and redux for state management.
In this application I have a reducer, which stores the current state of the user's presence. So whether the user is online or offline. I'm getting the current state of the user's presence using the useSelector hook.
My question however is how to get previous value stored in the userStatus object.
reducer.js
import * as actionTypes from "../actions/types";
import { combineReducers } from "redux";
const initialState = {
userStatus: { value: "unavailable", label: "Offline" },
};
const user_reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.SET_USER_STATUS:
return {
...state,
userStatus: action.payload,
};
default: {
return state;
}
}
};
const rootReducer = combineReducers({
user: user_reducer,
});
export default rootReducer;
//getting user current presence
const userPresence = useSelector((state) => state.user.userStatus);
example:
current State `userStatus: { value: "unavailable", label: "Offline" }`
previous state userStatus: { value: "available", label: "Online" }
How can i get this previous state
After updating the state in redux, use useEffect on change of that redux state and save that state in some local state. In this case whenever redux state updates you'll have that previous state stored in local
function Component(props){
const userPresence = useSelector((state) => state.user.userStatus);
const [userLocal, setUserLocal] = useState(null)
useEffect(()=>{
// here you have access to previous state(userLocal) and current
// state(userPresence)
setUserLocal(userPresence)
},userPresence)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With