1

How do i make an api call first in redux action and then dispatch GET_TODOs?

// first the api call has to be made,

    export function getTodos() {
    return {
          type: 'GET_TODOS',
          promise: request.get(API_URL)
      }
    }

then it need to parse the response

// using https://github.com/Leonidas-from-XIV/node-xml2js
parseString(res, function (err, result) {
          // data gets parsed here
});

Then it has to send the raise the event. I tried as below but it is throwing error

const request = axios.get(url).then(res=>{
parseString(res, function (err, result) {
if(result){
      dispatch({
         type: GET_TODOS,
      data:result
    })
}
if(err) throw err
   });
}).catch(err=>console.error(error))
  };

I am getting below error

Error: Actions must be plain objects. Use custom middleware for async actions.

StateLess
  • 5,344
  • 3
  • 20
  • 29
kobe
  • 15,671
  • 15
  • 64
  • 91

1 Answers1

4

Use thunk middleware. Here's how your action would look like:

export const GET_TODOS = 'GET_TODOS'
export const GET_TODOS_SUCCESS = 'GET_TODOS_SUCCESS'
export const GET_TODOS_FAILURE = 'GET_TODOS_FAILURE'

export function getTodos() {
  return dispatch => {
     dispatch({
        type: GET_TODOS
     })

     fetch(url) // or whatever way you're making API call
        .then(res => {
           parseString(res, (err, result) => {
              if (err) {
                 throw err
              }

              dispatch({
                 type: GET_TODOS_SUCCESS,
                 payload: result
              })
           })
        })
        .catch(err => {
              dispatch({
                 type: GET_TODOS_FAILURE,
                 payload: err
              })
        })
  }
}
craftsman
  • 15,133
  • 17
  • 70
  • 86
  • looks very clean, i am using the following redux boilerplat, do you think if i just replace promise middleware with thunk and it automatically work? https://github.com/bananaoomarang/isomorphic-redux – kobe Sep 30 '16 at 14:49
  • I am using axios to make the call as it works both on client and server side for isomorpchc – kobe Sep 30 '16 at 14:49
  • 1
    @kobe You can do that, but I don't think thunk middleware requires you to remove promise middleware. See this http://stackoverflow.com/a/36578210/162461 – craftsman Oct 01 '16 at 08:01