0

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?

Anil_M
  • 10,893
  • 6
  • 47
  • 74
user16516348
  • 117
  • 8

4 Answers4

1

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]);
}
Amruth
  • 5,792
  • 2
  • 28
  • 41
  • I'm actually using typescript so im getting `Type '{ id: number; label: string; }' is not assignable to type 'never'.` error. It says that `const selectedTag[] : never` EDIT: Fixed it. Just had to add a type to the selectedTag state. – user16516348 Aug 05 '21 at 06:03
  • https://stackoverflow.com/questions/52423842/what-is-not-assignable-to-parameter-of-type-never-error-in-typescript this should help you – Amruth Aug 05 '21 at 06:15
0

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

Mustafa ERK
  • 68
  • 1
  • 6
0

Try this

const addTag = (id: number)=> {
        tags.map(tag => {
            if(tag.id === id){
const tags = [...selectedTag];
tags.push(tag);   
                setSelectedTag(tags);
            }
        })
    }
Neel Dsouza
  • 1,342
  • 4
  • 15
  • 33
0

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])
Anil_M
  • 10,893
  • 6
  • 47
  • 74