skip to Main Content

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?

3

Answers


  1. I am not sure of what you want to achieve. Check if this code works for you:

    const listOfFields = ['field1', 'field2', 'field3'];
    
    const initialState = listOfFields.reduce((acc, field) => {
      acc[field] = true;
      return acc;
    }, {});
    
    const [all, setAll] = useState(initialState);
    
    Login or Signup to reply.
  2. const listOfFields = ['field1','field2','field3'];
    const obj = {}
    listOfFields.forEach(field => { obj[field] = true })
    const [all, setAll] = useState(obj);
    
    Login or Signup to reply.
  3. Yes, all you have to do is remove the current object with three properties and add an object with four properties in it.

    Example:
    setAll({ field1: true, field2: true, field3: true, field4: true }]

    Now the state update triggers a re-render of your UI to reflect its latest value.

    Keep in mind that React does not track changes if you directly mutate the array, even though it is passed by reference. For React to recognize that you made a change to your state using its setter function, you need to call the setter explicitly.

    Furthermore:

    If you want a mechanism to bind a defined array listOfFields into this state you may take advantage of the useEffect hook by map the array into your object and set the state. the array you define either needs to pass in as props to the component or have it as a state itself.

    If you pass the array as props whenever the prop changes it triggers a re-render of your component.

    OR

    If you make the listOfFields itself a state, whenever the state changes the component re-renders and takes its latest value.

    You have to use one of the methods to inform React that a change has been made to your object.

    Example code:

    useEffect(() => {
        const listOfMappedObject = listOfFields.map(field => ({ [field]: true }));
        //set the state
        allState(listOfMappedObject)
    }, [listOfFields]) 
    
    // Whenever listOfFields changes function inside this hook runs.
    
    // You have to pass this listOfFields either as props or a state itself for react to know that you have made a change to this list.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search