Skip to content

Instantly share code, notes, and snippets.

@Rajatgms
Created August 3, 2020 15:35
Show Gist options
  • Save Rajatgms/398ae9bc26280db745ba01f4356ce6b3 to your computer and use it in GitHub Desktop.
Save Rajatgms/398ae9bc26280db745ba01f4356ce6b3 to your computer and use it in GitHub Desktop.
Slice with lifecycle
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import fetchMarketItems from '../API/fetchMarketItems';
export const fetchAllItems = createAsyncThunk(
'items/fetchAllItems',
fetchMarketItems,
{
condition: (arg, api) => {
return !api.getState().items.length > 0;
},
},
);
const itemsSlice = createSlice({
name: 'items',
initialState: [],
reducers: {
saveItems: (state, action) => [...state, ...action.payload],
},
extraReducers: {
// if API successfully fetch all item save it to store items
[fetchAllItems.fulfilled]: (state, action) => [...state, ...action.payload],
},
});
const { actions, reducer } = itemsSlice;
export const { saveItems } = actions;
export default reducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment