ShocKwav3_
ShocKwav3_

Reputation: 1760

React & Redux: Dispatching action not working

I have a scenario where I am dispatching an action after an api call is successful.

axios.get(url)
       .then(response => {
         console.log("RESPONDED", response, dispatch)
         const payload = response
         dispatch(fetchSucess(payload))
       })

The snippet for fetchSucess:

const fetchSucess = (payload) => (dispatch) => {
  console.log("FETCH SUCCESS HAPPENED", payload)
  return {
    type: someActionTypes.FETCH_ALL_SUCCESS,
    payload,
  }
}

Now strangely FETCH_ALL_SUCCESS is not fired. if i replace the return with dispatch then it works. Why it is not working when I am dispatching it from the api callback? Help would really appreciated!

Upvotes: 0

Views: 279

Answers (2)

Vishal Sharma
Vishal Sharma

Reputation: 2610

Looking at the snippet, I'm assuming that you are using redux-thunk middleware (you forgot to mention that maybe?). In that case, the below approach is the right way. Here, fetchData is a thunk and fetchSuccess is an action.

const fetchSuccess = (payload) => ({
  type: someActionTypes.FETCH_ALL_SUCCESS,
  payload
})

const fetchData = () => (dispatch) => {
  axios.get(url)
     .then(response => {
       console.log("RESPONDED", response, dispatch)
       dispatch(fetchSuccess(response))
     })
}

Upvotes: 1

Volodymyr
Volodymyr

Reputation: 1408

You have this issue because fetchSuccess function is defined wrongly. If you will take a closer look you will notice that calling fetchSucess(payload) returns an arrow function:

(dispatch) => {
  console.log("FETCH SUCCESS HAPPENED", payload)
  return {
    type: someActionTypes.FETCH_ALL_SUCCESS,
    payload,
  }
}

while dispatch accepts an object so fetchSuccess function has to return an action object:

{
    type: someActionTypes.FETCH_ALL_SUCCESS,
    payload,
}

that is why fetchSuccess function should look similar to this:

const fetchSucess = (payload) => {
  console.log("FETCH SUCCESS HAPPENED", payload)
  return {
    type: someActionTypes.FETCH_ALL_SUCCESS,
    payload,
  }
}

Upvotes: 1

Related Questions