0

I wanna be able to create a hashmap using a javascript object with dynamic keys using useState in react hooks. What I figured so far is that to append a new key value pair, I can just do the following:

const [map, setMap] = useState({});
setMap({...map, [key]:[value]});

But then, how would you be able to push onto that array? After doing some research, I tried doing the following two methods:

setMap({...map, [key]: [...[key], value]})

and

setMap({...map, [key]: [...map[key], value]})

But both don't work. The former just gives me the actual key with the value appended, meaning it is forever stuck to just two values(which is not what I want because I want to be able to push multiple values onto the array).

The Latter just gives me a an error stating that map[key] is not iterable, which is also quite confusing to me since when I console log map[key], it gives me the object with correct key value pair (albeit with only 2 items in the array, which is just the key and the latest value).

So how would you correctly push values onto this array? Thanks in advance!

1 Answer 1

3

Your second version is close. It will work if map[key] is already set

But otherwise map[key] is undefined, and trying to spread [...undefined] will give you the not iterable error

You can first define the currentValues, and if none use an empty array

const addValueToMap = (key, newValue) => {
  const currentValues = map[key] || []; // get current values for the key, or use empty array
  setMap({ ...map, [key]: [...currentValues, newValue] })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. It went over my head how map[key] would initially be undefined, thus the error I was getting.

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.