Reputation: 117
I have a some state like this :
const [tags, setTags] = useState([{id: 1, label: "random"}, {id: 2, label: "important"}])
const [input, setInput] = useState("")
const [selectedTag, setSelectedTag] = useState([])
and below that somewhere i have a function like this :
const addTag = (id: number)=> {
tags.map(tag => {
if(tag.id === id){
setSelectedTag(tag) // trouble here
}
})
}
I want to push the new selected tag into the state of selectedTags which is an array, how do i push the tag into that array when i can't even access selectedTags state directly?
Upvotes: 0
Views: 53
Reputation: 11443
See useState reference at useState hooks API reference
useState does not automatically merge values, However you can mimic it as follows,
Warning : following code is not tested.
const addTag = (id: number)=> {
tags.map(tag => {
if(tag.id === id){
setSelectedTag([... selectedTag],...[tag])
}
})
}
Edit: In order to have clean code following will work better. Which is basically same as @amruth. Above code will be better useful if you are merging two arrays.
setSelectedTag([... selectedTag, tag])
Upvotes: 0
Reputation: 5912
You should do this way.
const addTag = (id: number)=> {
tags.map(tag => {
if(tag.id === id){
setSelectedTag([...selectedTag, tag]);
}
})
}
this could be another way to do the same job.
const addTag = (id: number)=> {
let tag = tags.find(tag => tag.id === id);
setSelectedTag([...selectedTag, tag]);
}
Upvotes: 1
Reputation: 1539
Try this
const addTag = (id: number)=> {
tags.map(tag => {
if(tag.id === id){
const tags = [...selectedTag];
tags.push(tag);
setSelectedTag(tags);
}
})
}
Upvotes: 0
Reputation: 66
Use Array.Filter or Array.find for get selected tag
Example for your code:
const addTag = (id: number)=> {
const filteredTag = tags.find(tag => tag.id === id))
setSelectedTag(filteredTag);
}
find return object
Upvotes: 0