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?

4 Answers 4

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]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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

Comments

0

Try this

const addTag = (id: number)=> {
        tags.map(tag => {
            if(tag.id === id){
const tags = [...selectedTag];
tags.push(tag);   
                setSelectedTag(tags);
            }
        })
    }

Comments

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])

Comments

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.