Sign in

Fetching and Storing Data In React

Through most of my projects during my time at Flatiron School I have been using a fetch request to get information from an API and display it on a frontend application. Now, having gone through the course work on React, I have an understanding on how to not only fetch information in a React App but also how to store and display that data. Here’s how I organized the steps in my brain.

Using Thunk Middleware in Store

First I have to create the store that will house all of the data fetched from the API.

Above is the store that I have created using Thunk and the ItemsReducer made earlier. Here I have imported createStore, and applyMiddleware from redux, the ItemsReducer from my Reducer folder, and thunk from redux-thunk. I then simply create the store variable and set it equal to createStore. createStore takes in two arguments of the ItemsReducer and applyMiddleWare. I then passed in thunk to applyMiddleWare to create applyMiddleWare(thunk).

Creating fetch request action

Next we need to create the fetch request to our API. For this request I will be using a Rails API that I created for my final project.

Here, I created the constant fetchItems that will return a function that takes in dispatch. In the return function I have added the fetch request to the API. Then I parsed out the response through to return json. Finally the last lines dispatch an action object of type: “GET_ITEMS”. Thunk allows us to have action creators return a function so we can do asynchronous logic within the actions instead of the components.

Items Reducer

Finally I need to create a reducer function that will take argument of initial state and an action.

In the function I have a switch statement that has a value of action.type. Next I set the case as the same I named my action object in my fetch request. In this case that is “GET_ITEMS”. Finally I return the action payload and then return the state.