0
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.

1 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.