0

My reducer is:

case TOGGLE_TABLE:
      const newState = { ...state };
      const activeTable = newState.list.find((table: any) => table.id === action.id);
      if (activeTable.visible === undefined) activeTable.visible = false;
      else delete activeTable.visible;

      return newState;

To my understanding, I am mutating state here, is there some quick fix to make sure I don't?

0

1 Answer 1

1

Use findIndex to find the activeTable instead, and assign a new array to the .list which contains a new activeTable object:

const newState = { ...state };
const { list } = newState;
const activeTableIndex = list.findIndex((table) => table.id === action.id);
const newActiveTable = { ...list[activeTableIndex] };
if (newActiveTable.visible === undefined) newActiveTable.visible = false;
else delete newActiveTable.visible;
newState.list = [...list.slice(0, activeTableIndex), newActiveTable, list.slice(activeTableIndex + 1)];
return newState;

Or, if there will never be more than one matching id, you might consider .map to be more elegant:

const newState = { ...state };
const newList = newState.list.map((table) => {
  if (table.id !== action.id) return table;
  const newActiveTable = { ...table };
  if (newActiveTable.visible === undefined) newActiveTable.visible = false;
  else delete newActiveTable.visible;
  return newActiveTable;
});
newState.list = newList;
return newState;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.