Skip to content
Advertisement

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

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 ?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement