2

I've searched the react documentation, as well as several questions here and this article, but I'm confused as to how to accomplish this task. https://goshakkk.name/array-form-inputs/

I'm trying to iterate over a nested state object in a react application. the questions is an array of objects, each with title, description and options.

questions:   [
        {
          title:       'EKG',
          description: 'EKG changes affect risk',
          options:     [
            {
              value:       '1',
              description: 'ST Wave changes'
            }
          ],
        }

right now I'm just working with the title value before I work with the entire object.

I'm trying to create an event updater for the edit/new form, but I'm having trouble putting the question object back together to update state. Here is my form:

      {this.state.questions.map((q, i) => (
        <div>
          <label>Question {i+1 + '.'}</label>

          <input
            type="text"
            placeholder={`Question #${i+1}`}
            name="title"
            defaultValue={q.title}
            onChange={this.handleQuestionChange(i)}
          />
          <button type="button" className="small">-</button>
        </div>
        )
      )}

And here is my updater:

handleQuestionChange = (i) => (e) => {
    console.log(e.target.name, e.target.value, i)
    let stateCopy = Object.assign({}, this.state)
    const name = e.target.name
    const questions = stateCopy.questions.map((question, j) => (
      j === i ?
         question[name] = e.target.value
      :
        question[name] = question[name]

    ))
    console.log(stateCopy.questions, questions)
    stateCopy.questions = questions
    this.setState({questions: stateCopy.questions})
  }

it handles the first update fine, but since my conditional if statement in the handler squashes the object into one field, the 2nd update creates an error. I thought that question[name] would update the key:value pair, but it return NAN so I end up with this when logging the before and after question state:

{title: "EKG", description: "EKG changes affect risk", options: Array(1), NaN: "EKG4"}

changing the handler to this gets me closer...at least returns an object, but I can't access the variable name from e.target.value dynamically:

const questions = stateCopy.questions.map((question, j) => (
  j === i ?
     question[name] = {question: {name: e.target.value}}
  :
    question[name] = {question: {name: name}}

))

which gives me this for the question object, and eliminates the other two key value pairs. I don't think I need to manually iterate over every key: value pair just to set one of them.

{name: "EKGn"}

Any tips? I realize this may be more of a javascript / Object manipulation question than a react one, but i've tried several variations including using an string literal ES6 syntax for the dynamic name and it's still not working. x: question

1 Answer 1

1

The problem was in the .map function. I'm posting the working code here, in case it helps anyone else. I'm not sure what the etiquette is for answering your own question.

  const questions = stateCopy.questions.map((question, j) => {
      if (j === i ) question[name] = e.target.value;
      return question;
    })
Sign up to request clarification or add additional context in comments.

1 Comment

Self-answers are perfectly fine, although you have to wait until 48 hours after asking (So, in about 38 hours) to accept. Congrats!

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.