R
R
ravshan selimov2020-07-07 18:23:54
React
ravshan selimov, 2020-07-07 18:23:54

How to correctly change the state of redux, react-redux?

Hello.

I started to study redux, but I didn’t understand how to change the state (store) correctly, I

read several articles everywhere they say you need to use pure functions.
I know what pure functions are, but I still don’t understand how to change the state.

Now I do this

function reducer(state, action){

  switch (action.type) {

    case 'LOGGED': {

      return {
        isLogged : true,
        user: action.user 
      }

    };

    default: return state;

  }

}

export default reducer;

Correct or not?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Loli E1ON, 2020-07-07
@ravshan01

Just stick to data immutability:

return {
    ...state,          // Разворачиваем старое состояние
    isLogged : true,   // обновляем свойства которые нужно
    user: action.user  // обновляем свойства которые нужно
}

Immutability:
Immutable is an object whose state cannot be changed after creation. Any modification of such an object will always result in a new object, while the old object will not change.

P
Pavel Shvedov, 2020-07-07
@mmmaaak

change state + pure functions = a function that does not change the old state, but calculates and returns a new state based on the old one (and, in particular, also based on the received action)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question