Anonymous
Anonymous

Reputation: 13

How to append object with existing object in State and render in REACT?

let intialData = {
    person: {
     name: 'George',
     age: '21'
    }
   }
const [data, setData] = useState(intialData)

useEffect(() => {
    for (let i = Object.values(data).length + 1; i <= 3; i++) {
      setData([
        ...Object.values(data),
        {
          person: {
            name: '',
            age: ''
          }
        },
      ])
    }
  },[data])

With the initialData I create form in HTML with two fields Name and Age.

{name:'George', age: '21'}

But instead it creates like

[{name: '', age: ''},
{name: '', age: ''},
{name: '', age: ''}]

But I need to create like below

[{name: 'George', age: '21'},
{name: '', age: ''},
{name: '', age: ''}]

with the above code initially it renders with empty fields but after I clicked or type the initialData kick in. How to render with initialData from the first load.

Upvotes: 0

Views: 2388

Answers (1)

Piotr Żak
Piotr Żak

Reputation: 2132

focusing on structure:

if there is array of object of person:

person: {
 name: 'George',
 age: '21'
}

then data to match your type should be flatten - to avoid person duplicates:

let person = {
     name: 'George',
     age: '21'
   }

useEffect(() => {
    for (let i = Object.values(data).length + 1; i <= 2; i++) {
      setPeople([...Object.values(data),
        {
            name: '',
            age: ''
        },
      ])
     setPeople([...people, person]);
    }
  },[data])

Upvotes: 1

Related Questions