0

I'm trying to create a form in react, where I have the questions pulled from a flask backend as a dictionary, where in React it results in an object. As a result, I have the following code when the component is getting rendered:

const [questions, setQuestions] = useState('');
const [answers, setAnswers] = useState('');

/// answers are pulled from api, with questions and answers set up to be equal. 
... 

{ Object.entries(questions).map(([key, question]) =>
 (
   <>
     <p> {question}</p>
     <textarea value = {answers[key]} onChange = {(e) => setAnswers(prevAnswer => ({...prevAnswer, key:e.target.value}))} 
     type = 'text' required />      
   </>
 )
)
}

I can update the value with the keys, but I don't know how to accept a value to the associated key in the object.

Edit ** I found a relevant post from a while back...
How do you rerender a React component when an object's property is updated?

1 Answers1

0

I believe this bit:

<textarea 
  value={answers[key]}
  onChange={
    (e) =>
      setAnswers(prevAnswer => ({
        ...prevAnswer,
        key: e.target.value
      }))
  } 
  type='text'
  required 
/>

is just going to set the literal key "key" to the new value. Instead we want to do this:

<textarea 
  value={answers[key]}
  onChange={
    (e) =>
      setAnswers(prevAnswer => ({
        ...prevAnswer,
        [key]: e.target.value // <-- note `[key]:` here rather than `key:`
      }))
  } 
  type='text'
  required 
/>
CollinD
  • 7,304
  • 2
  • 22
  • 45