maher ben abdesslam
maher ben abdesslam

Reputation: 65

How To update react redux state

I got predefined data of the user who logged in with state with useSelectore at the top of the code, but when I want to change the values of the user's profile

onSubmit=
    {async values => {
                        await updateUser(values).then((data) => {
                        store.dispatch(setCurrentUser(data));
                        store.subscribe();
                        console.log("store", store.getState().auth.user);//it shows the state has been updated

      });
    }}

It changes in the View and got updated in the database, but when I refresh the page it shows the old same values from the store My reducer

const auth = createSlice({
name: 'auth',
initialState,
reducers: {
    setCurrentUser : (state, action) => {
        state.isAuthenticated = true;
        state.user = action.payload;

    }....})

The documentation of updating the state confuses me more

 function select(state) {
  return state.some.deep.property
 }

let currentValue
function handleChange() {
 let previousValue = currentValue
 currentValue = select(store.getState())

 if (previousValue !== currentValue) {
   console.log(
     'Some deep nested property changed from',
     previousValue,
     'to',
     currentValue
    )
 }
}

 const unsubscribe = store.subscribe(handleChange)
 unsubscribe()

Upvotes: 0

Views: 95

Answers (1)

Andreq Frenkel
Andreq Frenkel

Reputation: 1208

Redux is inmemory store. Then you refresh page it will disappear.

So you have to use localStorage or indexedDB to store your data.

Take a look into such library for better understanding https://github.com/rt2zz/redux-persist

You need to get initial state from localStorage, and persist your redux state to localStorage on every change.

const storeKey = 'your-unique-key-name';
function persist() {
    localStorage[storeKey] = JSON.stringify(store.getState);
}
store.subscribe(persist);

...
const initialState = localStorage[storeKey] ? JSON.parse(localStorage[storeKey]) : undefined;

Upvotes: 1

Related Questions