Home Why is my Redux State not updating despite recieving a valid Action Payload (Async Auth Call)

# Why is my Redux State not updating despite recieving a valid Action Payload (Async Auth Call)

Mikhail
1#
Mikhail Published in 2018-01-11 00:40:03Z
 I'm using Redux, and dispatching a Redux Thunk Fetch Call to a RESTful API in to validate Login Credentials. The API is successfully returning a JWT (Authorization Token) in the response. My Reducer is configured to update the Store with this Token, but it is returning "undefined" instead of the Token. I can see the Token within the Redux Logger Action Payload - so I'm not sure what's going on. I suspect this is because the API is not sending the Token quickly enough, and my Reducer is updating with an unresolved value. The Logs do suggest this, but I'm also confused why - When I open the action in the console.log, the state of the Promise fluctuates from pending to fulfilled within the same entry! I will post my Action + Reducer code and the pertinent console logs - I would highly appreciate if anyone could point me to the right direction of my mistake: /// REDUCERS const initialState = { isAuthenticated: false} const authReducer = (state = initialState, action) => { switch(action.type){ case ('USER_AUTHENTICATED'): { return Object.assign({}, state, { isAuthenticated: true, token: action.userInfo.token, } ) } case ('INVALID_CREDENTIALS'): { return Object.assign({}, state, { isAuthenticated:false } ) } default: return state } /// ACTIONS function authSuccess (userInfo) { return { type:'USER_AUTHENTICATED', userInfo } } function authFail () { return { type: 'INVALID_CREDENTIALS' } } export function attemptLogIn(credentials) { return dispatch => { return fetch('http://localhost:3001/authorize', { headers:{ 'Content-Type': 'application/json' }, method: 'POST', mode: 'cors', body: JSON.stringify(credentials) }) .then(response => response.ok ? dispatch(authSuccess(response.json())) : dispatch(authFail())) } }  Initially, the Redux Logs show the Action as a Pending Promise: This is reflected by the token being "undefined" When I open up the same action, however, I can clearly see that the state of the Promise has changed to a resolution and that the token is, in fact, there. I would assume that the authSuccess() dispatch would only fire after receiving (response.ok) - so how can the Promise still be pending? Appreciate any help!
Tareq
2#
 The reason is that you are dispatching reponse.json() which it self will return a promise Also, you need to pass json result back from fetch to authSuccess action creator Change the code to: .then(response => response.ok ? response.json() : throw new Error(response.statusText)) .then(json => dispatch(authSuccess(json)) .catch(err => dispatch(authFail()))