How to Use Redux thunk in React. React Redux Connect tutorial

redux thunk

Now let’s install redux, redux-thunk and react-redux.

Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store dispatch method, which is then used to dispatch regular synchronous actions inside the body of the function once the asynchronous operations have completed.

If you’re curious, a thunk is a concept in programming where a function is used to delay the evaluation of the operation.

npm install redux redux-thunk react-redux

Then After import the createStore function and the applyMiddleware function. What is middleware? Well, it is nothing but a piece of code that sits between your actions and your reducers. It takes your actions does something to it before passing it down to the reducer. Think of it like a middle-man.

createStore is used for creating the redux store while the applyMiddleware will be used for adding the thunk middleware.

createStore Code Inside index.js write the following:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import thunk from 'redux-thunk';
import {createStore,applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import {rootReducer} from './reducers';
class Root extends React.Component{
    render(){
        const store=createStore(rootReducer,applyMiddleware(thunk));
        return(
            <Provider store={store}>
                <App/>
            </Provider>
        )
        
    }
}
ReactDOM.render(<Root />, document.getElementById('root'));
serviceWorker.unregister();

Here we have imported the store that we created earlier inside index.js.

We are also making use of the Provider component that allows us to access the store state from our components. Hence we pass the App component which is the root component into the provider and passing the store as a prop.

Then After Create actions Directory. And In this Create One File Name: index.js

import axios from 'axios';

export const setArticleDetails(data) {
    return {
      type: "CHANGE_NAME",
      products: data
    };
}

export const GetData = () =>{
    return function(dispatch) {
        return  axios.get('API URL')
        .then((result) => {
            dispatch(setArticleDetails(result.data));
        })
    }   
}

In this First Import axios. You Can Also Use Fetch Library For Calling API. Both Are Similar.

What Is Axios?
Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js.

Installing.?
the most common way to install Axios is via the npm package manager:

npm i axios

and include it in your code where needed:

import axios from 'axios';

redux action returning function can accept two parameters. Those are dispatch and getState. This is great because with dispatch we can call other action creators. So now all we do for async operations is to do everything that will be async inside the returning function and then call the relevant action creators when the data comes back passing in the new data that we get from the API. The other relevant action creators in this case receive_post will then pass this new data in an action object to the reducer and then the reducer can update the application’s state with the new data.

So now we are Create One New Directory reducers in this Create Main index.js File.
this one file is used to combine Multiple reducers using combineReducers function. this is the redux default function.

write below code into reducer->index.js file.

import {combineReducers} from 'redux';
import datareducer from './productdata';

export const rootReducer=combineReducers({
             data:datareducer
})

 

then after Create one Reducer Call DataReducer. create other File into reducer directory DataReducer.

const dataState={
          products:[], // Default State
          status:0
          Message: Default Message
}
const dataReducer = (state=dataState,action) =&amp;gt; {
               switch(action.type)
                {
                   case "CHANGE_NAME":
                      return{
                          ...state,
                          products:action.products
                      }
                   default:
                      return state;
                }
}
export default dataReducer;

We have three switch cases. First Used CHANGE_NAME us used for getting Product Name. Finally, we have RECEIVE_ERROR which sets the error flag to true.

Now lets head back to App.js and start building the user interface and hook all this up.

import React from 'react';
import logo from './logo.svg';
import './App.css';
import {connect} from 'react-redux' // Used For Connaction Between Component And Actions file.
import {GetData} from './actions'
class App extends  React.Component{

  componentDidMount(){
    this.props.onChangeName()
  }
  render(){
    const product=this.props.products;
    return(
       
<div className="App">
         {(product != 0 && product.length  > 0)
          ?
          
<div>
            
<h1>This is React Component</h1>

              {product.map((product, index) => (
                
<h1>Name : {product.coinName}</h1>

               ))}
          </div>

         :null}
         <button >Change Name</button>
      </div>

 
    )
  }
}
const mapStatetoProps=(state)=>{
  console.log(state)
  return {
    products:state.data.products
  }
}
const mapDispatchtoProps=(dispatch)=>{
  return{
    onChangeName:()=>{
      dispatch(GetData())  // Set Product Data Into Store.
    }
  }
}
export default connect(mapStatetoProps,mapDispatchtoProps)(App);

If the above code feels weird to you I strongly suggest checking out my Redux article where I go in-depth about connect and how the above code works.

A lot going on here. First Component is Initialization automatic called componentDidMount. We have Directory Called onChangeName actions function. then After Call Display On App.js We Are Used Connect Method.
Connect Method in Used mapDispatchtoProps,mapStatetoProps. These Two Method Called Before Initionlization of Component.
This Method To Product Name Are Get Into API and Set Into Redux Store.

Then Props Method You Can use And Get The Data For Partiqual Component. then We have used a map to list out Product Name.

Thanks for reading this long article and I will be back with another one.

LEAVE A REPLY

Please enter your comment!
Please enter your name here