Redux-toolkit: How to set initial value for createEntityAdapter API

Created on 11 Apr 2020  路  3Comments  路  Source: reduxjs/redux-toolkit

getInitialState how to set some initial values,
I did this below but it didn't work.

const sizeAdapter = createEntityAdapter();

export const { reducer, actions } = createSlice({
  name: 'responseSize',
  initialState: sizeAdapter.getInitialState([
    {
      id: 'a',
      todo: 'one'
    },
    {
      id: 'b',
      todo: 'two'
    }
  ]),
  reducers: {
    changeSize: sizeAdapter.updateOne
  }
});

Snipaste_2020-04-12_00-45-30

Most helpful comment

The getInitialState() function just returns an empty {ids: [], entities: {}} object.

You could use the CRUD methods to further manipulate that outside the slice, then use the result as the initial state:

const emptyInitialState = sizeAdapter.getInitialState();
const filledState = sizeAdapter.upsertMany(emptyInitialState, items);

const sizeSlice = createSlice({
  name: "responseSize",
  initialState: filledState,
  reducers: {}
})

All 3 comments

I think what you're looking for is preloadedState in configureStore. The usage of getInitialState() is for adding additional properties to the reducer and setting their default values like:

adapter.getInitialState({ loading: '', errorMessage: '' })

But I cannot use the CRUD method to manipulate data outside of these Entity, such as: addOne, addMany, removeOne, updateOne ... etc.

The getInitialState() function just returns an empty {ids: [], entities: {}} object.

You could use the CRUD methods to further manipulate that outside the slice, then use the result as the initial state:

const emptyInitialState = sizeAdapter.getInitialState();
const filledState = sizeAdapter.upsertMany(emptyInitialState, items);

const sizeSlice = createSlice({
  name: "responseSize",
  initialState: filledState,
  reducers: {}
})
Was this page helpful?
0 / 5 - 0 ratings