Search code examples
javascriptreactjsdictionaryredux

Add item to beginning of an Map Object with "unshift" method


  const { items, ids } = action.payload;
  const { fetchedItems } = state;
  const diff = _.difference(state.ids, action.payload.ids);
  // @APPEND
  for (let i = 0; i < items.length; i++) {
    fetchedItems.set(items[i].id, items[i]);
  }
  // @DELETE
  for (let i = 0; i < diff.length; i++) {
    fetchedItems.delete(diff[i]);
  }
  const myArray = Array.from(fetchedItems.values());
  return {
    ...state,
    items: Array.from(fetchedItems.values()), // not for use
    fetchedItems,
    ids: action.payload.ids,
    syncStatus: action.payload.tocMeta.syncStatus
  };

Quesstion is: my API based on sockets and every time i am receive new object, i am use Map object for ease update and delete and everything working nice, i want to set new items which coming from action.payload object on the first index of the Map "like unshift", can you provide some trick for that? Because new Map().Set() put the new items in the bottom of the Map object, and i don't want to do Map.clear() every time.


Solution

  • I don't think there's a nice way to do it. The order of a Map is determined by insertion order, so if you want an a specific value to be first, then your only option is to see to it that it gets inserted first.

    I'm also not sure if using Map is actually a good idea in this case. In Redux, you're not supposed to mutate the state like you do in your for-loops (modifying the Map). That makes Maps pretty hard to work with in Redux, as you would need to constantly make copies of your Map before you could safely use methods like .set or .delete.

    The creator of Redux has said (about Set and Map)

    I don’t think it’s a good idea to use them in Redux because they are optimized for mutability. If you want to have something efficient with similar semantics, consider using Immutable.js.

    So I would probably switch back to using an array which have convenient non-mutating methods like .map and .filter (and works with the ... syntax), or maybe an object (with id as key, and you can use your ids to keep track of the order).