Getting Data from the Server

Learn how to fetch data from the server.

Fetching data from a server, like anything with Redux, happens as a result of a dispatched action. In our case, the UI should dispatch an action when it loads to ask Redux to bring data to the store.

For this, we will need to add a new constant to constants/actionTypes.js and a new action creator in actions/recipes.js. Our action will be called FETCH_RECIPES:

export const fetchRecipes = () => ({
  type: FETCH_RECIPES
});

Sadly, we cannot handle the action inside a reducer. Because the action requires server access that might take time, our reducer will not have the capacity to handle the response. In this case, reducers should return the modified state immediately.

Luckily, we have middleware, which has access to the store and thus the store’s dispatch() method. This means we can catch the action in middleware, submit a network request, and then send a new action to the reducers with the data already inside.

Get hands-on with 1200+ tech skills courses.