React, Axios and Redux: Asynchronously Fetch and Save Data to Local Storage
In this post we will give you information about React, Axios and Redux: Asynchronously Fetch and Save Data to Local Storage. Hear we will give you detail about React, Axios and Redux: Asynchronously Fetch and Save Data to Local StorageAnd how to use it also give you demo for it if it is necessary.
In this tutorial, we’ll learn about many of Redux concepts by creating a simple React application from scratch using React, Redux and Axios to asynchronously fetch and save data to Local Storage.
Note: If you are consuming any other resource, make sure you have CORS enabled so the browser doesn’t disallow reading the remote resource due to the Same Origin Policy.
The app will also include a favorites page where you can add and delete your favorite JS terms from the jargon.
These are the steps of our tutorial:
- Step 1 — Installing Create-React-App & Initializing a React Application
- Step 2 — Installing Axios, Redux, React-redux and Redux-thunk
- Step 3 — Creating Redux Actions
- Step 4 — Creating Redux Reducers
- Step 5 — Creating the Redux Store
- Step 6 — Creating the React Component
- Step 7 — Saving Data to Local Storage
Redux is an implementation of the Flux pattern – An application architecture for building user interfaces which are created and used by Facebook.
Redux is a library for managing the state of your application which is usually used with React, but it can also be used with other libraries and frameworks. It works by using a global state store common between all the components of the application.
Why Using Redux?
Redux is a good solution for medium and large apps which can help you handle complex state management requirements. But it’s not needed in every use case.
For example, if you have components with many children and you want to pass state down the children tree, you can use the React Context API for accessing state in any component at any level without passing state to components that don’t actually need it just because it’s needed by a child component.
For more information, read You Might Not Need Redux by Dan Abramov, the creator of Redux.
We will need a few prerequisites for this tutorial, such as:
- A recent version of Node.js and NPM installed on your system,
If you have the previous prerequisites, let’s get started with the first step where we’ll install the
create-react-app utility and create a React app.
Step 1 — Installing Create-React-App & Initializing a React Application
In this step, we’ll install the
create-react-app utility, next we’ll proceed to initialize our React project.
Open a new terminal and run the following command:
$ npm install -g create-react-app
Note: You may need to add
sudo before your command in Linux and macOS or use a CMD with administrator access if you want to install packages globally on your system. You can also simply fix your npm permissions.
At the time of this writing create-react-app v3.1.1 is installed.
Now, we are ready to create our React project. Head back to your terminal and run the following command:
Next, navigate inside your project’s folder and run the following command to start the local development server:
Your application will be available from the
In the next step, we’ll install Axios, Redux,
Step 2 — Installing Axios, Redux, React-redux and Redux-thunk
In the previous step, we have created our React project and served it locally. In this step, we’ll install Axios, Redux, its React bindings and also redux-thunk.
Open a new terminal, navigate inside your project’s folder and run the following command:
$ npm install --save redux react-redux redux-thunk
Redux-thunk is a middleware that extends Redux to let you write asynchronous logic that interacts with the store. For example for fetching data from remote resources.
Next, we also need to install Axios:
$ npm install axios --save
Step 3 — Creating React Redux Actions
According to the official docs:
Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch().
type property which indicates the type of the action being performed. For example in our case, we can create an action of type
In most cases, an action can also include data:
In this example, the event name is
ADD_FAVORITE_TERM and the data is the name.
src folder, create a folder called
$ cd src$ mkdir actions
Next, navigate inside the
actions folder and create a
$ cd actions$ touch types.js
types.js file using your preferred code editor (We’ll be using the nano editor):
$ nano types.js
Next, add the following constants and save the file:
Next, create an
index.js file inside the
$ touch index.js
Open the file using your code editor:
$ nano index.js
Next, start by adding the following code to the
We imported our
REMOVE_FAVORITE_TERM action types that we previously defined in the
actions/types.js file. We also imported the
axios client and defined the
apiUrl constant variable which holds the URL of our JSON API.
Next, in the same
actions/index.js file define the two following methods:
These two methods are called action creators,
Action creators are simply functions that create and return actions.
We first defined the
addFavoriteTerm() function that creates and returns an action of the
ADD_FAVORITE_TERM type and provides the action with a data payload comprised of the name and description, passed as an argument to the function, of the JS term that users are adding to their favorites.
Next, we defined the
removeFavoriteTerm() function that creates and returns an action of the
REMOVE_FAVORITE_TERM type and
name payload which refers to the name of the JS term that users want to remove from their favorites.
Now, we need to define a function that fetches data from the JSON API and dispatches an action of the
ADD_FETCHED_DATA type with the fetched data as the payload as follows:
Notice that this function is different from the previous functions (action creators) because it performs an asynchronous operation and returns a function, instead of an object, which has a passed
This function is called a thunk action creator.
According to Wikipedia:
A thunk is a subroutine used to inject an additional calculation into another subroutine. Thunks are primarily used to delay a calculation until its result is needed, or to insert operations at the beginning or end of the other subroutine. They have a variety of other applications in compiler code generation and modular programming.
fetchData() thunk, we first return a function that takes a dispatch argument. In the body of the returned function we call the
If the Promise is successfully resolved, we send an action of the
ADD_FETCHED_DATA type, along with the data fetched from the API as the payload, to the store using the passed
An action creator can return a function instead of an action object thanks to the Redux Thunk middleware which comes from the redux-thunk package we previously installed and which we’ll add later to our Redux store.
Dispatching an action is simply sending the action to the Redux store. Typically, we dispatch actions from the UI following user reactions. In the case of asynchronous operations like network requests we can also dispatch actions from action creators.
That’s all we need to define our actions. In the next step, we’ll see how to use reducers to change the state of the application after dispatching actions.
Step 4 — Creating React Redux Reducers
In this step, we’ll see what a reducer function is and we’ll add reducers to our application.
Before writing the reducers, it’s essential to think about the shape of your application’s state.
Head back to your terminal and, inside the
src/ folder, create a
reducers folder and navigate to it using the following commands:
$ cd ..$ mkdir reducers$ cd reducers
Next, create the
favoritesReducer.js files using the following commands:
$ touch index.js$ touch termsReducer.js$ touch favoritesReducer.js
$ cd ..$ nano reducers/termsReducer.js
Next, add the following code:
We first import the
ADD_FETCHED_DATA action type and next we define and export a pure function that takes the old state and action and returns a new state depending on the type of action. In this case if the
ADD_FETCHED_DATA action is sent we simply return a new state with the action payload (the array of data fetched from the JSON API).
Next, open the
$ nano reducers/favoritesReducer.js
And add the following code:
Again, we import the
REMOVE_FAVORITE_TERM action types, next we define and export a pure function that takes the old state and an action, and returns a new state depending on the action.
If the action type is
ADD_FAVORITE_TERM, we create a new state comprised of the old state and the new favorite term sent with the action payload. If it’s
REMOVE_FAVORITE_TERM, we call the filter method on the state array to remove the term by name from the state. If none of these actions are sent, we return the old state.
We have now created reducers for mutating the various pieces of the global state of our application. We need to combine these reducers into one reducer using the combineReducers() method. Open the
$ nano reducers/index.js
Next, add the following code:
We first imported the
combineReducers() method and our two reducers from their respective files, Next we called the
combineReducers() method by passing an object that takes the keys that will be used for each slice of our global state and assigns the required reducer.
combineReducers() generates a function that calls the required reducer for each slice of the state, and combines their results into a single object.
For more detailed information about reducers, make sure to read this page of the official docs.
In the next step, we’ll see how to configure the Redux store in our application.
Step 5 — Creating the React Redux Store
Now, that we have defined the actions and reducers in our application, we need to create the store.
$ nano index.js
Next, start by adding the following imports:
Next, create the store as follows and send the action for fetching data from the JSON API:
First, we created the store and applied the
redux-thunk middleware to the store which allows us to support asynchronous actions in Redux.
Next, we dispatched our first action for fetching data from the server and storing it in the store.
Next we need to pass the store to the components. In the same file, wrap the
App component with the
Provider component as follows:
We pass the store as a prop to
In the next step, we’ll see how to create a React component for displaying our data.
Step 6 — Creating the React Component
In this step, we’ll create a
JargonList component for displaying the list of JS terminologies that you have consumed from the API. We’ll also display the favorite terms selected by users in this same component and use conditional rendering to switch between the lists of terms and favorites.
Head back to your terminal and create a
JargonList.js file in the
src/ folder of your project:
$ touch JargonList.js
$ nano JargonList.js
Next, start by adding the following imports:
Next, define the following method which will be used to map the state from the Redux store to the component props:
Next, let’s create the component as follows:
Next, we need to define the following two methods in the
JargonList class to toggle between the jargon and favorites views:
Finally, we need to connect the component to the Redux store and export it:
connect() method enables you to access the dispatch method as a prop by returning a new component with the dispatch method as its prop.
Next, open the
$ nano App.js
Next, update it as follows:
We simply included our
JargonList component in our
App component so it gets rendered when the app is started.
Next, we’ll see how to persist the favorite terms using localStorage.
Step 7 — Saving Data to Local Storage
In this step, we’ll add support for storing the favorite JS terms added by the user using the local storage of the browser so they can be persisted between app refreshes.
$ nano index.js
Next, let’s implement the following changes.
First, you need to define these two methods:
getState() function gets the state from
localStorage using the
getItem() method for retrieving the stored string and the
Finally, we need to retrieve the saved state from localStorage and pass it as the initial state of the store:
This way when the user visits the app again, the store will be initialized of the favorites data from localStorage.
Finally, we need to subscribe to the Redux store and call the
saveState() function with the user favorites whenever an action is dispatched.
This way, when we send an action to add a favorite or remove a favorite from the store the corresponding local storage will be updated.
This is the full code of the
src/index.js file after these updates:
In this tutorial, we’ve seen step by step how we can build a React application and manage its state using Redux.
You can find the source code of this application from this GitHub repository.
Hope this code and post will helped you for implement React, Axios and Redux: Asynchronously Fetch and Save Data to Local Storage. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs