0

I am currently still new at typescript and i do not know if i am doing the things right . I want to update my array and i want to set an initial state as an empty array. At the moment i am doing this :

 const [selectValue, setSelectValue] = useState<Array<string>>([]);

And my update function is this :

const handleChange = (e: any) => {
    setSelectValue((selectValue: any) => [{ ...selectValue, [e.target.value]: e.target.name }]);
  };

And the output is this :

0: {Ananas : "A"} , Banana : "B"

What am i doing wrong , because i want my output to be equal to one object like this :

0: {Ananas : "A" , Banana : "B"}

1 Answer 1

1

If you want to have only one item inside the array that collect all the keys then you have to do something like this:

const handleChange = (e: any) => {
  setSelectValue((selectValue: any) => {
    const newSelectValue = [...selectValue]
    if (!newSelectValue[0]) newSelectValue[0] = {}

    return newSelectValue.map((value, index) => {
      if (index === 0) {
        return { ...value, [e.target.value]: e.target.name }
      } else {
        return value
      }
    })
  })
};
Sign up to request clarification or add additional context in comments.

4 Comments

Btw, I believe you are mutating the state here newSelectValue[0]. While newSelectValue refers to new array, newSelectValue[0] refers to state value (old array), which should be immutable by the default.
@captain-yossarian yes you're right. I updated the answer in order to get rid of that mutability. What do you think now? It's better?
Pls remove const newSelectValue = [...selectValue] if (!newSelectValue[0]) newSelectValue[0] = {}
Why? If the array is empty and we not init the first element in that way, when we map the array it will do nothing.

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.