How to fetch data from Api in Redux using Redux-thunk

How to fetch data from Api in Redux using Redux-thunk

In this post we will give you information about How to fetch data from Api in Redux using Redux-thunk. Hear we will give you detail about How to fetch data from Api in Redux using Redux-thunkAnd how to use it also give you demo for it if it is necessary.

we will learn about how to fetch data from the API in redux by using the redux-thunk middleware.

Getting started

We are using the create-react-app command line tool to generate the new react app boilerplate.

npx create-react-app http-redux

This above command will download the react app related files inside the “http-redux” folder.

Change your working directory to “http-redux” by using below commands.

cd http-reduxnpm start

npm start command is used to turn on the react app development server.

Connecting react with redux

Now we need to make a connection between the react and redux libraries for that we need to downloadtwo packages from the npm.

Run the following commands to install the redux and react-redux packages.

npm i redux react-redux

Redux is a state management library for JavaScript apps.

React-redux is used to make a connection between react and redux.

Open your “http-redux” folder using your favorite code editor and create a new folder called reducersinside your src directory.

In reducers folder create a new file called myreducer.js and add the below code.

myreducer.js
const intialState = {    num: 0}const reducer = (state = intialState, action) =&gt; {    <span>switch (action.type) {        case "INCREMENT":            return { num: state.num + 1 }        default:            return state    }}export default reducer

Here we just created a small reducer function with one action type “INCREMENT”.

Open your index.js file and the below code.

index.js
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import { createStore } from 'redux'import { Provider } from 'react-redux'import reducer from './reducers/myreducer'const store = createStore(reducer);ReactDOM.render(&lt;Provider store={store}&gt;    &lt;App /&gt;&lt;/Provider&gt;, document.getElementById('root'));

Now We successfully connected react with redux.

Synchronous action creators

Synchronous action creators are just functions which return an object with the type ofaction and payload.

Let’s create a synchronous action creator.

create a new file called actions.js in your src folder.

actions.js
export const increment = () =&gt; {    return {        type: "INCREMENT"    }}

Let’s use this action creator to dispatch the INCREMENT action.

App.js
import React, { Component } from 'react';import './App.css';import { connect } from 'react-redux'import { increment } from './actions'class App extends Component {  render() {    return (      &lt;div className="App"&gt;        &lt;h1&gt;{this.props.num}&lt;/h1&gt;        &lt;button onClick={this.props.onIncrement}&gt;Increment&lt;/button&gt;      &lt;/div&gt;    );  }}const mapStatetoProps = (state) =&gt; {  return { num: state.num }}const mapDispatchtoProps = (dispatch) =&gt; {  return {    onIncrement: () =&gt; dispatch(increment())  }}export default connect(mapStatetoProps, mapDispatchtoProps)(App);

This asynchronous action creator example.

Asynchronous action creators

Asynchronous action creators don’t return the object immediately with action type and payload instead of it returns the function with parameters dispatch and getState.

Because in asynchronous code like if we fetching something from the backend API it takes some time to get the data from the backend so that we are not dispatching the action immediately instead of we are dispatching the action only when the data comes back from the backend API.

For Asynchronous actions we need to install a new package called redux-thunk.

npm i redux-thunk

redux-thunk is a middleware which helps us to delay the actions to dispatch.

If you want to learn about thunks then check out my previous tutorial.

once you successfully installed the ‘redux-thunk’ now we need to configure our code to use thismiddleware.

Open your index.js and update with redux-thunk configuration.

index.js
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';import { createStore, applyMiddleware } from 'redux'import thunk from 'redux-thunk'import { Provider } from 'react-redux'import reducer from './reducers/myreducer'const store = createStore(reducer, applyMiddleware(thunk));ReactDOM.render(&lt;Provider store={store}&gt;    &lt;App /&gt;&lt;/Provider&gt;, document.getElementById('root'));

First, we imported applyMiddleware function from the ‘redux’ library then we imported ‘thunk’ from the ‘redux-thunk.

Next, we invoked the applyMiddleware function by passing the thunk as its argument.

Update your reducers.js file with below code.

const intialState = {    num: 0,    data: null,    error: ""}const reducer = (state = intialState, action) =&gt; {    switch (action.type) {        case "INCREMENT":            return { ...state, num: state.num + 1 }        case "FetchData":            return { ...state, data: action.data }        case "ERROR":            return { ...state, error: action.msg }        default:            return state    }}export default reducer

We are updated our reducer.js file by adding a two new action types “FetchData” and “ERROR”.

Let’s create an asynchronous action creator which helps us to fetch the data.

update your actions.js file with the below code.

actions.js
// synchronous action creatorexport const increment = () =&gt; {    return {        type: "INCREMENT"    }}// asynchronous action creatorexport const fetchData = () =&gt; {    return (dispatch) =&gt; {        return fetch('https://jsonplaceholder.typicode.com/todos/1')            .then(response =&gt; response.json())            .then(json =&gt; dispatch(                { type: "FetchData", data: json }))            .catch(err =&gt; dispatch(                { type: "ERROR",msg: "Unable to fetch data" }))    }}

In the above code, we only dispatch the FetchData action whenever the data arrives from the API and we dispatch the ERROR action in case an error occurs while fetching the data.

Let’s dispatch the asynchronous action creator in our App component.

App.js
import React, { Component } from 'react';import './App.css';import { connect } from 'react-redux'import { fetchData } from './actions'class App extends Component {  componentDidMount() {    this.props.onFetchData()  }  render() {    return (      &lt;div className="App"&gt;        &lt;h1&gt;Fetching the data from the backend&lt;/h1&gt;        {this.props.error &amp;&amp; &lt;p&gt;{this.props.error}&lt;/p&gt;}        {this.props.data &amp;&amp; &lt;ul&gt;          &lt;li&gt;id: {this.props.data.id}&lt;/li&gt;          &lt;li&gt;title: {this.props.data.title}&lt;/li&gt;        &lt;/ul&gt;}      &lt;/div&gt;    );  }}const mapStatetoProps = (state) =&gt; {  return { num: state.num, data: state.data, error: state.error }}const mapDispatchprops = (dispatch) =&gt; {  return { onFetchData: () =&gt; dispatch(fetchData()) }}export default connect(mapStatetoProps, mapDispatchprops)(App);

In the App component we called the this.props.onFetchData() function inside thecomponentDidMount() life cycle method.

Output:

Code repository

Hope this code and post will helped you for implement How to fetch data from Api in Redux using Redux-thunk. 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

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US