Search code examples
reactjsecmascript-6

Adding values dynamically inside useState in ReactJS


I have below code where I am hardcoding field1, field2, field3. I have an array of fields from where I want to generate this object inside useState. Is it possible to do it?

const listOfFields = ['field1','field2','field3'];

 const [all, setAll] = useState({
    field1: true,
    field2: true,
    field3: true
  });

I want useState to take field1, field2, field3 from the list of fields so that if the list of fields has some additional fields like field4, useState will use it automatically

Is it possible to dynamically generate an object inside useState using listOfFields?


Solution

  • const listOfFields = ['field1','field2','field3'];
    const obj = {}
    listOfFields.forEach(field => { obj[field] = true })
    const [all, setAll] = useState(obj);