Search code examples
reactjstypescriptreduxredux-toolkit

How do I find an object in a redux array using TypeScript?


Here is my slice.ts file.

interface iItem {
  Category: string;
  Id: string;
}

interface iDataState {
  Items: Array<iItem>;
}

const initialState: iDataState = {
  Items: [],
};


reducers: {
  updateItem: (state, action: PayloadAction<iItem>) => {
    console.log(state.Items);
  }
}

Every time I run dispatch(updateItem(data)); in a component, I see Proxy(Array) {0: {…}} in the console.

How can I update an item in Items if I can't access Items to search for the item to update?


Solution

  • I suppose you are using redux toolkit

    Rtk is wrapping your reducer function with immerjs (https://redux-toolkit.js.org/usage/immer-reducers).

    This allow you to compute you next state by mutating the current state.

    Immer allow this by wrapping the state in a proxy which reimplement all the method of Array like find.

    If you want to log the wrapped state for debugging sake, you can use the function current exported by immer console.log(current(state));