Home > Software engineering >  How can I add a string to a string value inside an object?
How can I add a string to a string value inside an object?

Time:07-22

What im trying to do is to add a string id next to a value inside of an object. So the object is like this:

["John","Mike"]

An item in the object is generated as soon the user clicks an add button

  const handleAddClick = () => {
    setLanguage([...language, ""]);
  };
  const handleItemChanged = (event, index) => {
    const value = event.target.value;
    const list = [...subtitle];
    if (list.filter((f) => f === value).length > 0) {
      setErrorValidation("Names cannot be equal!");
    } else {
      setErrorValidation("");
    }

    list[index] = value;
    setName(list)
  };

In the handleItemChanged, I tried to do this, but it didn't work.

let string = "test"

list[index] = value   string;
setName(list)

So what I want is to add a string to a new value that is added to the list

["Johntest", "Miketest"]

How can I solve this?

CodePudding user response:

You can use map before assigning value:

// ... the other code is omitted for the brevity
list.map(item => item   "test") 
setName(list)

An example:

let arr = ["John", "Mike"]
arr = arr.map(item => item   " test")
console.log(arr)

CodePudding user response:

Calling setName(list) does not trigger a rerender for the simple reason that list is still the same object. setState will only work if the previous and new value is different. For objects, they are shallowly compared.

That is why it is suggested to create a new array using .map():

let string = "test"
const newList = list.map(e => e urString)
setName(newList)
  • Related