I am trying to fetch the Rick and Morty API and display an info card about each character. There are 826 characters in total separated in 42 pages. I am not sure how to fetch all different pages at once... so I came up with this for loop solution.
const [characters, setCharacters] = useState([]);
const fetchData = () => {
let allCharacters = [];
for (let i = 1; i <= 42; i++) {
fetch(`https://rickandmortyapi.com/api/character?page=${i}`)
.then((response) => {
return response.json();
})
.then((data) => {
allCharacters.push(data.results);
});
}
setCharacters(allCharacters);
};
useEffect(() => {
fetchData();
}, []);
The problem is that I am getting the desired data stored twice in the State and when looping through it to display the cards I get 1600 characters. Any suggestion how I could improve my fetching technic? The API structure looks like this:
{
"info": {
"count": 826,
"pages": 42,
"next": "https://rickandmortyapi.com/api/character?page=2",
"prev": null
},
"results": [
{
"id": 1,
"name": "Rick Sanchez",
...
I have seen this question already posted in stackoverflow but there they also get double the data... that is why I ask again and sorry for the similar post! Thanks!