E
E
eugenedrvnk2021-12-12 12:45:07
JavaScript
eugenedrvnk, 2021-12-12 12:45:07

What is the best way to structure logic in redux?

There is an action to update an element:

reducers: {
  ITEM_UPDATED: (state) => {
    ...someCode...
  }
}


Then it becomes necessary to update not one element, but several, which solution would be more correct here:

1. Create a sledge to update several elements and from there call each update in turn:
const updateItems = () => (dispatch) => {
  const items = axios.get('...');
  items.forEach(( item ) => dispatch(ITEM_UPDATED, item))
}


2. Transfer the handler for updating the element into a separate function and reuse it.
const handleItemUpdated = (state) => {
  ...
}

reducers: {
  ITEM_UPDATED: (state, item) => handleItemUpdated(state, item);
  ITEMS_UPDATED: (state, items) => {
    items.forEach(( item) => handleItemUpdate(state, item));
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-12-12
@Alexandroppolus

The correct option is to write a separate handleItem s Update function, which should create a copy of the array and replace the incoming elements in this copy. Or even replace the massif, if you don’t need to merge the old and the new.
handleItemUpdate does an array replacement for the sake of one element, and calling it multiple times is completely inefficient.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question