Home > other >  How to modify data received from fetch Request in React
How to modify data received from fetch Request in React

Time:01-23

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})
      })));
  }, []); ```
 

CodePudding user response:

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,
        })),
      }));
    );
}, []);
  • Related