简体   繁体   中英

Add object to existing state if it doesn't exist, update it if exists React state

I have a <button> that creates an <input> element onClick , it also assigns to it a name attribute based on number of childNodes of parent element. Currently I update EXSITING object value, however I would like it to create a new object in the existing state data1 if it doesn't exist.

PS : The first input element created has a name of datapoint9 .

//State data1 with existing objects

const [data1, setData1] = useState({
  datapoint:"", 
  datapoint2:"", 
  datapoint3:"", 
  datapoint4:"", 
  datapoint5:"", 
  datapoint6:"", 
  datapoint7:"", 
  datapoint8:"", 
 }) 

 <button onClick={ (e) => {

// Create input element 

const add = document.createElement("input");

// Number of child Nodes parent element has 

const numberparentNodes = document.getElementById("parent").childNodes;

console.log(check)

add.type = "text"

// Assigned name based on number of Childs parent has
add.name = `datapoint${numberparentNodes.length-6 }`



// This updates value of existing object within the state without removing other objects

 add.onchange= (e) => {
 setData1({...data1 , [e.target.name]: [e.target.value] } )
 }

document.getElementById("parent").appendChild(add);

}}> Create </button>

You don't have to handle DOMs elements like you did. You should always manipulate them using react, I've wrote a code to do what you want, please ask if you have doubts:

import { useState } from "react";

export default function App() {
  const [data, setData] = useState({
    datapoint1: "",
    datapoint2: "",
    datapoint3: "",
    datapoint4: ""
  });

  const handleClick = () => {
    setData({
      ...data,
      [`datapoint${Object.keys(data).length + 1}`]: ""
    });
  };

  const handleChange = (datapoint) => (event) =>
    setData({
      ...data,
      [datapoint]: event.target.value
    });

  return (
    <div className="App" style={{ display: "flex", flexDirection: "column" }}>
      <button onClick={handleClick}>Click to add</button>
      {Object.keys(data).map((datapoint) => {
        return (
          <input
            style={{ margin: "20px" }}
            key={datapoint}
            onChange={handleChange(datapoint)}
          />
        );
      })}
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM