The Simplest Guide to Understand Redux-Thunk

Credit: Redux-Thunk Kunfu
npx create-react-app my-app
//default importimport React from "react";import ReactDOM from "react-dom";import "./index.css";import App from "./components/App/index";
// necessary imports for redux and thunkimport {createStore, applyMiddleware} from "redux";import {Provider} from "react-redux"import thunk from "redux-thunk";import {reducer} from "./store/reducers/reducers"const store = createStore(reducer, applyMiddleware(thunk))ReactDOM.render(<Provider store={store}><App /></Provider>,document.getElementById("root"));
import {createStore, applyMiddleware} from "redux";
$ npm install  — save redux-thunk 
const store = createStore(reducer, applyMiddleware(thunk))
const getSoupDataFromAPIAsync=(products)=>{return {type:"get_products", payload:products}}export const loading = ()=>{   return {type:"isLoading", payload:true}}export const getSoupDataFromAPI=()=>{   return (dispatch)=>{     dispatch(loading())     fetch("http://shopsoup.herokuapp.com/api/v1/product")     .then((data)=>{     return data.json()   }).then((products)=>{dispatch(getSoupDataFromAPIAsync(products))})}}
const getSoupDataFromAPIAsync=(products)=>{return {type:"get_products", payload:products}}
export const getSoupDataFromAPI=()=>{
return (dispatch)=>{ dispatch(loading()) setTimeout(()=>{ console.log("success")
dispatch(success())
}, 5000)})
export const getSoupDataFromAPI=()=>{    return (dispatch)=>{        dispatch(loading())       fetch("http://shopsoup.herokuapp.com/api/v1/product")        .then((data)=>{       return data.json()   }).then((products)=>{    dispatch(getSoupDataFromAPIAsync(products))})
const initialState = {products:[]}export const reducer=(state=initialState, action)=>{     const newState = {          ...state        }switch(action.type){   case "get_products":       return {         loading:false,         products:action.payload,          };   case "loading":       return {       loading:true       }   }return newState;}
 this.props.dispatch(actionCreators.getSoupDataFromAPI())
Sample

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store