How to fetch data through api in redux?

bier hier picture bier hier · Oct 2, 2016 · Viewed 41.5k times · Source

I am a beginner with reactjs/redux, could not find a simple to use example of how to use an api call to retrieve data in a redux app. I guess you could use a jquery ajax call but there are probable better options out there?

Answer

cdagli picture cdagli · Oct 2, 2016

JSfiddle; http://jsfiddle.net/cdagli/b2uq8704/6/

It uses redux, redux-thunk and fetch.

Fetch methods;

function fetchPostsWithRedux() {
    return (dispatch) => {
    dispatch(fetchPostsRequest());
    return fetchPosts().then(([response, json]) =>{
        if(response.status === 200){
        dispatch(fetchPostsSuccess(json))
      }
      else{
        dispatch(fetchPostsError())
      }
    })
  }
}

function fetchPosts() {
  const URL = "https://jsonplaceholder.typicode.com/posts";
  return fetch(URL, { method: 'GET'})
     .then( response => Promise.all([response, response.json()]));
}

Actions used above:

(Note: You can define many actions e.g. fetchPostRequest can be used to display a loading indicator. Or you can dispatch different actions in case of different HTTP status codes.)

function fetchPostsRequest(){
  return {
    type: "FETCH_REQUEST"
  }
}

function fetchPostsSuccess(payload) {
  return {
    type: "FETCH_SUCCESS",
    payload
  }
}

function fetchPostsError() {
  return {
    type: "FETCH_ERROR"
  }
}

And in your reducer you can load the posts to state;

const reducer = (state = {}, action) => {
  switch (action.type) {
    case "FETCH_REQUEST":
      return state;
    case "FETCH_SUCCESS": 
      return {...state, posts: action.payload};
    default:
      return state;
  }
} 

You can access the state and actions within your component after connecting them with;

connect(mapStateToProps, {fetchPostsWithRedux})(App);