Home > Blockchain >  problem dynamically changing the form's state
problem dynamically changing the form's state

Time:02-01

I have an array inside values and I would like to change state using the "name" property inside the form but it doesn't work. What am I doing wrong?

const initialFlashcardState = {
  collection_name: '',
  prompt: '',
  answers: ['1', '2', '3', '4'],
  right_answer: 1,
};

const [values, setValues] = useState(initialFlashcardState);

const handleInputChange = (e) => {
  const { name, value } = e.target;
  setValues({
    ...values,
    [name]: value,
  });
};

return (
  <Controls.Input
    label='First Answer'
    name='answers[0]'
    value={values.answers[0]}
    onChange={handleInputChange}
  />
);

CodePudding user response:

you are trying to change property called answers[0] and that is a string. here is the codesandbox link

although it is not the best approach to this it's better to use an object array for this

CodePudding user response:

If you want to keep your data structure I would suggest to pass index to handleInputChange as long as your inputs are ordered:

const handleInputChange = (e, index) => {
    const { value } = e.target
    setValues({
        ...values,
        answers: [
          ...values.answers.slice(0, index),
          value,
          ...values.answers.slice(index   1)
    })
}

/* ... */

<Controls.Input
  label="First Answer"
  value={values.answers[0]}
  onChange={e => handleInputChange(e, 0)}
/>

CodePudding user response:

I think that you should define a dedicated function to do that:

  const [values, setValues] = useState(initialFlashcardState);
  
  const handleFirstAnswerChange = (e) => {
      const newAnswer = e.target.value;
      const updatedAnswers = values.answers;
      if (updatedAnswers.length > 0) {
        updatedAnswers[0] = newAnswer;
      } else {
        updatedAnswers.push(newAnswer)
      }
      setValues({
          ...values,
          answers: updatedAnswers
      })
  }
  return (
    <Controls.Input
      label='First Answer'
      value={values.answers[0]}
      onChange={handleFirstAnswerChange}
    />
  );
  •  Tags:  
  • Related