1

I written code a dynamic form whose codes are given below, but my problem is in storing it in the useState formFields , which is stored in an array / Each object is stored separately, but I want them to be stored in an array ‍‍question.

this is my input:

[
{ titleQuestion: "aaa", metric: "bbb", subMetrico: "ccc" },
{ titleQuestion: "bbb", metric: "bbb", subMetrico: "ccc" },
{ titleQuestion: "ccc", metric: "bbb", subMetrico: "ccc" }
]

but i want to be like this:

{
    "quetions": [
          { titleQuestion: "aaa", metric: "bbb", subMetrico: "ccc" },
          { titleQuestion: "bbb", metric: "bbb", subMetrico: "ccc" },
          { titleQuestion: "ccc", metric: "bbb", subMetrico: "ccc" }
        
    ],
}

​ this is my all code:

  const [formFields, setFormFields] = useState([])

  // Add Question
  const handleFormChange = (event, index) => {
    let data = [...formFields];
    // data[index][event.target.name] = event.target.value;
    setFormFields(data);
  }

  const submit = (e) => {
    e.preventDefault();
    console.log(formFields)
  }

  const addFields = () => {
    let object = {
      titleQuestion: '',
      metric: '',
      subMetrico:''
    }

    setFormFields([...formFields, object])
  }

  const removeFields = (index) => {
    let data = [...formFields];
    data.splice(index, 1)
    setFormFields(data)
  }

and:

<div className="App">
      <form onSubmit={submit}>
        {formFields.map((form, index) => {
          return (
            <div key={index}>
              <input
                name='titleQuestion'
                onChange={event => handleFormChange(event, index)}
                value={form.titleQuestion}
              />
              <input
                name='metric'
                onChange={event => handleFormChange(event, index)}
                value={form.metric}
              />
               <input
                name='subMetric'
                onChange={event => handleFormChange(event, index)}
                value={form.subMetric}
              />
              <button onClick={() => removeFields(index)}>Remove</button>
            </div>
          )
        })}
      </form>
      <button onClick={addFields}>+</button>
      <br />
      <button onClick={submit}>submit</button>
    </div>

UPDATE:

{
    "quetions": [
          { titleQuestion: "aaa", metric: "bbb", subMetrico: "ccc" },
          { titleQuestion: "bbb", metric: "bbb", subMetrico: "ccc" },
          { titleQuestion: "ccc", metric: "bbb", subMetrico: "ccc" }

    ],
     "post_id":10
}
4
  • 1
    You're initialising formFields as an array, so you get an array... if you want an object, then initialise it with an object. Moreover, this sounds like an XY problem: even if you're storing in as an array now, nothing is stopping you from transforming it into an object later if you need to pass it on for other uses. Commented Oct 15, 2022 at 20:05
  • @Terry Sorry, I didn't understand what you meant Thank you. If you can, please edit my code so that I can understand my mistake Commented Oct 15, 2022 at 20:16
  • I edited the code he means for you Commented Oct 15, 2022 at 20:17
  • Note that I just everywhere referenced your array inside an object with a questions key Commented Oct 15, 2022 at 20:18

1 Answer 1

1

You need to change the following functions so that your array is stored inside the questions key in the object

  const [formFields, setFormFields] = useState({})

  // Add Question
  const handleFormChange = (event, index) => {
    let data = [...formFields.quetions];
    // data.quetions[index][event.target.name] = event.target.value;
    setFormFields({ quetions: data });
  }

      const addFields = () => {
        let object = {
          titleQuestion: '',
          metric: '',
          subMetrico:''
        }
    
        if(formFields.quetions)
            setFormFields({ quetions: [...formFields.quetions, object] });
        else 
            setFormFields({ quetions: [object] });
      }

  const removeFields = (index) => {
    let data = [...formFields.quetions];
    data.splice(index, 1)
    setFormFields({ quetions: data })
  }
Sign up to request clarification or add additional context in comments.

34 Comments

You should now write like this: formFields.questions.map because your array is now stored inside the questions key in the object
This is because in the first run there is no key named questions, you can fix this by initializing this key at the beginning like this: const [formFields, setFormFields] = useState({questions: []}) Or add a question mark in the map in the following way: formFields.questions?.map
If you use typescript then you cannot use the second solution, you can write like this: formFields.questions && formFields.questions.map
Can you print to the console the value of formFields after you press + and send here?
Note that your key is quetions, and in the map I wrote questions by mistake (or in the initialization of the usestate from the previous comment), please correct everything to the exact same keyword
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.