0

The question is how to modify data received from fetch Request in React?

1)I get the result of a fetch request and put in into state 2)To work with the data I need to modify it (add an ID and a boolean to each item of the array inside one of the objects of the coming array.

I tried the following way, but it doesn't work:

useEffect(() => {
    fetch(
      "https://opentdb.com/api.php?amount=5&category=10&difficulty=easy&type=multiple"
    )
      .then((res) => res.json())
      .then((data) => data.map(question => ({
        ...question,
        incorrect_answers: question.incorrect_answers.map(answer => {...answer, isSelected: false})
      })));
  }, []); ```
 

1
  • can you post the expected result after modifying it? Commented Jan 23, 2023 at 8:48

1 Answer 1

2

Your data is a object so you can't map over it. The data object has a property results which contains the array of questions.

data.results.map((question) => ({ ... })

Then the first time you correctly surround the object you return with () but when you map over the incorrect_answers you don't.

incorrect_answers: question.incorrect_answers.map((answer) => ({
  ...answer,
  isSelected: false,
}));

Full code

useEffect(() => {
  fetch(
    "https://opentdb.com/api.php?amount=5&category=10&difficulty=easy&type=multiple"
  )
    .then((res) => res.json())
    .then((data) =>
      data.results.map((question) => ({
        ...question,
        incorrect_answers: question.incorrect_answers.map((answer) => ({
          answer,
          isSelected: false,
        })),
      }));
    );
}, []);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but inside of incorrect_answers I have a string, not an object, I need to modify the string to be the value answer of a key of a new created object.
I updated my answer to not use the spread operator on the answer value, now incorrect_answer will be a array of object with the props answer and isSelected. Could explain what you mean by he value answer of a key of a new created object?
I mean that I need to change answer from string to object, because at the moment it's a string, maybe that's why the code isn't working...
The code's working, thanks a lot for your help. Problem solved:)

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.