Search code examples
reduxslicetoolkit

How i can get some ids from entity (redux toolkit)?


I have Redux Toolkit - slice, entityAdapter

How i can remove messages for one channal by channel ID?

const messagesAdapter = createEntityAdapter();

const messages = createSlice({
  name: 'messages',
  initialState: messagesAdapter.getInitialState(),
  reducers: {
    addMessage: messagesAdapter.addOne,
  },
  extraReducers: {
    [channels.actions.removeChannel]: (state, action) => {
      const idCahnnel = action.payload;
      const idsForRemove = // how i can get ids here? if i have idCahannel only
      // message look like { id: 1, idChannel: 2, nickname: 'nickname', text: 'sometext' }
      // i cannot filter state.entity because state is a Proxy here
      messagesAdapter.removeMany(state, idsForRemove);
    },
  },
});

Solution

  • You can do operations against the existing state and its nested fields like state.entities. Yes, the "draft state" has been wrapped in a Proxy, but you can interact with the values as if it were still a plain JS object like normal.

    See the Redux Toolkit docs page on Writing Reducers with Immer for instructions on how to correctly work with Immer's draft state values.