Search code examples
reactjsonchange

In react how do I get only the last value for a onchange function


I'm new to react. I'd like to collect the value from an input in an array of objects. But on the input's onChange it adds all the letters to the array. I'd like to collect only the last entry. How may I do that ?

 <input
                type="text"
                placeholder="Ecrivez votre question"
                onChange={(event) => {
                  let tab = [...questionsTitle];
                  tab.push({
                    index: index,
                    type: questionType[index],
                    title: event.target.value,
                  });
                  setQuestionsTitle(tab);
                }}
              ></input>

As you can see on the screenshot, my array is very long. How can I get the value without going through all the letters ?

I thanks you in advance.

screenshot


Solution

  • Update the value if it already exist otherwise push the new object. Below is the sample code

    <input
    type="text"
    placeholder="Ecrivez votre question"
    onChange={(event) => {
        let tab = [...questionsTitle];
        let tabIndex = tab.findIndex(x => x.index === index);
        if (tabIndex !== -1) {
            tab[tabIndex].type = questionType[index]
            tab[tabIndex].title = event.target.value
        } else {
            tab.push({
                index: index,
                type: questionType[index],
                title: event.target.value,
            });
        }
        setQuestionsTitle(tab);
    }}