I
I
Incold2020-02-15 23:30:56
React
Incold, 2020-02-15 23:30:56

Why is state not updating in Redux store?

Hello! For a couple of hours I've been puzzling over why the state is not updated.
There is an action that sends the value of the fields in the form (login and password) to the server and receives a response from it in the form of a regular string.

function app (state=initialState, action) {
  if (action.type === 'LOGIN') {
    if (!Object.keys(state.loginValue).length) return state;
    else {
      let data = JSON.stringify(state.loginValue);
      axios.post('http://localhost:80/signin', data, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(res => {
        if (res.data !== 'All ok!') {
          console.log(res.data); // Здесь всё хорошо, ответ от сервера (строка) приходит
          return { // Здесь, по идее, должно происходить обновление state, но оно не срабатывает 
            ...state,
            loginWarning: res.data 
          };
        }
      })
      .catch(() => state)
    }
  }
  ...
  return state;
}


I set subscribe to state, and it does not work, because no change. How to fix it? Thanks in advance for any help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Demian Smith, 2020-02-15
@Incold

1. There should be no asynchronous operations in the reducer. Remove axios from the reducer. That won't work.
2. You need a thunk. Here is an example of how it is done correctly https://alligator.io/redux/redux-thunk/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question