Search code examples
reactjsreduxredux-toolkit

How to update UI after 2 seconds after showing Loading and using setTimeout in createAsyncThunk


I am trying to display the dishes which is rendered on home component after showing loading for 2 sec but unable to do this. I have doubts in createAsyncThunk part mostly.

// This is the structure of DISHES which i am importing
// DISHES = [
    {id: 0, name: "Uthappizza", image: "/assets/images/uthappizza.png", category: "mains",label: "Hot",},
    {id: 1,name: "Zucchipakoda",image: "/assets/image/zucchipakoda.png",
category: "appetizer",}]

const initialState = {
    isLoading: true,
    errMsg: null,
    dishes: [],
};
export const getDishes = createAsyncThunk("dishes/getDishes", () => {
    //return setTimeout(() => {
        //return DISHES;
    //}, 2000);
// I have tried to convert it like this
return DISHES;

//And from useEffect I am using setTimeout
});
export const dishesSlice = createSlice({
    name: "dishes",
    initialState,
    reducers: {},
    extraReducers: {
        [getDishes.pending]: (state) => {
            state.isLoading = true;
        },
        [getDishes.fulfilled]: (state, action) => {
            console.log(action);
            state.isLoading = false;
            state.dishes = state.dishes.concat(action.payload);
        },
        [getDishes.rejected]: (state) => {
            state.isLoading = false;
        },
    },
});

export default dishesSlice.reducer;

after above file I am trying this in home component but it is not working I am not getting correct values in payload on dishes/fullfilled action In redux devtools action is dispatching successfull and showing loading but after that there is error

import { getDishes } from "../redux/stateSlices/dishesSlice";

const { dishes, isLoading } = useSelector((state) => state.dishes);
const dispatch = useDispatch();
useEffect(() => {
// upadated code and using setTimeout here
       setTimeout(()=>{
         dispatch(getDishes());
      },2000)
    }, []);

if(isLoading){
return <Loading/>
}else {
return (...)
}

Now it is rendering ui as expected. First displaying the loading... for 2 seconds then showing home page but Now the problem here is that redux actions are getting called continuously and it is overloading the memory. Like one it is loading it should show pending and once it is loaded is should show fullfilled but the pending and fullfilled cycle goes on continuously


Solution

  • The function won't return promise. Please update like this.

    () => {
        return new Promise((resolve)=>{
            setTimeout(() => {
               resolve(DISHES);
            }, 2000);
        });
    }