Created
August 3, 2020 15:35
-
-
Save Rajatgms/398ae9bc26280db745ba01f4356ce6b3 to your computer and use it in GitHub Desktop.
Slice with lifecycle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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