How to add value to Map initialized in state using react?

Viewed 2429

I have application and i need to keep search history, in my opinion Map is suitable here:

const [searchHistory, setSearchHistory] = useState(new Map());

to update it use setSearchHistory(new Map([[text, result.repos]])); but it replaces Map with new Map, could you please tell me how can i add value to Map initialized in state ?

2 Answers

State updater function returned by useState doesn't merges the state like this.setState() in class-based components. In functional components, you have to manually merge the old state with the new state.

You are passing the new Map object to setSearchHistory, so it will completely overwrite the old state.

You could update the state by first copying the entries in the old Map object in to new Map object, then add the new entry you want to add in the state. Finally, pass this new Map object to setSearchHistory.

// copy (shallow) the old map's entries in the new Map
const updatedMap = new Map(searchHistory);  
// add the new entry in the 'updatedMap'
updatedMap.set(key, value);
// update the state
setSearchHistory(updatedMap);

You can achieve that like the following:

const [searchHistory, setSearchHistory] = useState(new Map());

function onChange(key, value) {
  // change the searchHistory map with a new Map from the current searchHistory, and the new key, value
  setSearchHistory(new Map([...searchHistory, [key, value]]));
}
Related