1

I am trying to update the state using React Hooks. I have an array of objects, within an object is another array I am trying to update. All these are generated dynamically.

[
    {
      "question": 2,
      "choices": ["Heart Disease", "GERD", "ASTMA"]
    },
    {
      "question": 4,
      "choices": ["Heart Disease", "GERD", "ASTMA"]
    },
    {
      "question": 9,
      "choices": ["Heart Disease", "GERD", "ASTMA"]
    }
  ]

My state looks like this. I am creating a form that contains multiple choices for different questions on the same page. So if I am on question 2, I want to be able to add (or remove) to the choices on that question.

How can I do this using useState?

2
  • If above is saved in state? What is the other object you want to save in state? What exactly you mean by I want to be able to add (or remove) to the choices on that question.? Commented Apr 15, 2020 at 5:30
  • Add some of your current code would help Commented Apr 15, 2020 at 5:33

2 Answers 2

1

In order to update the nested state, you need to map over the state and update the specific question id.

Here is the code for adding and removing choices.

let initialState = [
    {
        "question": 2,
        "choices": ["Heart Disease", "GERD", "ASTMA"]
    },
    {
        "question": 4,
        "choices": ["Heart Disease", "GERD", "ASTMA"]
    },
    {
        "question": 9,
        "choices": ["Heart Disease", "GERD", "ASTMA"]
    }
];

const [questions, setQuestions] = React.useState(initialState);

const addChoice = (questionId, choice) => {
    setQuestions(question.map(q => {
        if(q.question === questionId){
            return {...q, choices: [...q.choices, choice]}
        }
        return q;
    }))
};

const removeChoice = (questionId, choice) => {
    setQuestions(question.map(q => {
        if(q.question === questionId){
            return {...q, choices: q.choices.filter(c => c !== choice)}
        }
        return q;
    }))
};
Sign up to request clarification or add additional context in comments.

Comments

0

In case you meant that you need to change the choices based on the question number dynamically. Then maybe below should do the job. It is written on the fly and not tested.

const [questions, setQuestions] = React.useState(defaultObject);

function questionSelected(questionNumber) {
    const temp = questions;
    const question = temp.find(n => n.question == questionNumber);
    question.choices = ['New', 'Choices'];
    setQuestions([...temp]);
}

Hope it helps.

Comments

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.