Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous stored from an an object in redux

Tags:

reactjs

redux

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

like image 737
Coderops Avatar asked Dec 07 '25 02:12

Coderops


1 Answers

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)
}
like image 104
Harshit Upadhyay Avatar answered Dec 08 '25 20:12

Harshit Upadhyay