Redux thunk and API calls

npm -i redux-thunk
//store.js
import {legecy_createStore as createStore, applyMiddleware } from 'redux'
import thunk from "redux-thunk"
import reducer from './reducer'

const store = createStore(reducer, applyMiddleWare(thunk))
export default store
import * as actionTypes from "./actionTypes";
//action.js
export const addTask=(task)=>{
 return {
            type:actionTypes.ADD_TASK,
            payload:{task:task}
        }
}

export const removeTask=(id)=>{
 return {
            type:actionTypes.REMOVE_TASK,
            payload:{id:id}
        }
}

export const completedTask=(id)=>{
 return {
            type:actionTypes.TASK_COMPLETED,
            payload:{id:id}
        }
}

export const fetchTodo=()=>{
        return async function(dispatch, getState){
        const response = await fetch(
         "https://jsonplaceholder.typicode.com/todos"
            );
        console.log(response);
        const task= await response response.json();
        dispatch(addTask(task.title)) 
            }
}

instead of returning an object we can return function after using thunk , without thunk it will give error

remove unsubscribe

//index.js
import store from "./store"
import {addTask, removeTask, completedTask} from  "./action"

const unsubscribe=store.subscribe(()=>{
    cosole.log("Updated",store.getState())
})

store.dispatch(addTask("task1");
store.dispatch(addTask("task2");
console.log(store.getState());



store.dispatch(completedTask(2));
store.dispatch(removeTask(1);
console.log(store.getState());

connect me on linkedin: linkedin.com/in/swapnilxi

Redux dev tools

download from chrome store and put the installation script in the line