technology logo
technology logo

Redux toolkit thunk

share link

by bilal4 dot icon Updated: Dec 7, 2022

Guide Kit Guide Kit  

import {

 createAsyncThunk,

 createSlice,

 configureStore,

} from "@reduxjs/toolkit";


export const fetchProduct = createAsyncThunk("fetchproduct", async () => {

 const data = await fetch("https://fakestoreapi.com/products");

 return data.json();

});


const productSlice = createSlice({

 name: "product",

 initialState: {

  isLoading: false,

  isError: false,

  data: [],

 },

 extraReducers: (builder) => {

  builder.addCase(fetchProduct.pending, (state, action) => {

   state.isLoading = true;

  });

  builder.addCase(fetchProduct.fulfilled, (state, action) => {

   state.isLoading = false;

   state.data = action.payload;

  });

  builder.addCase(fetchProduct.rejected, (state, action) => {

   console.log("Erros is :", action.payload);

   state.isError = true;

  });

 },

});


export const productAction = productSlice.actions;

export const store = configureStore({

 reducer: productSlice.reducer,

});