'Is there any way that I can add another value to a key in an object within React?
I will have a list of objects that are going to be entered by an input field. I have it working where it will create the list of objects, but when I try to add another value to one of the objects that already exist. It will just replace the previous value within it.
Current output when I console.log()
const [ tags, setTags ] = useState({
1: 'hello',
2: 'world',
3: 'goodbye'
})
My expected output if person 1 adds the tag 'testing'.
const [ tags, setTags ] = useState({
1: ['hello', 'testing'],
2: 'world',
3: 'goodbye'
})
The function that I have so far that is taking the value from the input. A is an id number and B is the new tag.
function updateTags(a, b){
if(tags.hasOwnProperty(a)){
setTags((prevTags) => {
return {
...prevTags,
[a]: ????
}
})
}else{
setTags((prevTags) => {
return {
...prevTags,
[a]: b
}
})
}
If you need more information please let me know.
Solution 1:[1]
I think this should work
function updateTags(a, b){
if(tags.hasOwnProperty(a)){
setTags((prevTags) => {
return {
...prevTags,
[a]: Array.isArray(prevTags[a]) ? [...prevTags[a], b] : [prevTags[a], b]
}
})
} else {
setTags((prevTags) => {
return {
...prevTags,
[a]: b
}
})
}
Solution 2:[2]
I think you can use approach like this:
updateTags = (key, tag) =>
setTags((prevTags) => ({
...prevTags,
[key]: prevTags[key] ? [prevTags[key], tag].flat() : tag,
}));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | thalesbruno |
| Solution 2 | A1exandr Belan |
