Skip to content

Commit

Permalink
fetch pokemon and data
Browse files Browse the repository at this point in the history
  • Loading branch information
felixtanhm committed Apr 30, 2024
1 parent 84e4789 commit 9ac8d38
Showing 1 changed file with 52 additions and 14 deletions.
Original file line number Diff line number Diff line change
@@ -1,23 +1,61 @@
import { useState, useEffect } from "react";
import useSWR from "swr";
import { useState } from "react";

async function fetchList(endpoint) {
const response = await fetch(endpoint);
const result = await response.json();
function PokeList() {
const [list, setList] = useState(null);
const [state, setState] = useState("loading");
const [error, setError] = useState(null);
const endpoint = list ? list.next : `https://pokeapi.co/api/v2/pokemon/`;
console.log(list);

return result;
}
async function fetchList() {
try {
const response = await fetch(endpoint);
const result = await response.json();

function PokeList() {
const [list, setList] = useState({});
const endpoint = list.next ? list.next : `https://pokeapi.co/api/v2/pokemon/`;
if (result.results) {
const { count, next, previous } = { ...result };
const nextList = { count, next, previous, data: [] };
await Promise.all(
result.results.map(async (item) => {
try {
const singleResponse = await fetch(item.url);
const singleResult = await singleResponse.json();
item = { ...item, ...singleResult };
nextList.data.push(item);
} catch (error) {
console.log({ ...item, error });
}
})
);
setList(nextList);
setState("success");
}
} catch (error) {
console.log(error);
setState("error");
// setError(error);
}
}

if (state === "error") {
return <p>error</p>;
}

if (!list) {
console.log("api called");
fetchList();
}

if (state === "loading") {
return <p>loading...</p>;
}

const { data, error, isLoading } = useSWR(endpoint, fetchList);
console.log({ data, error, isLoading });
return (
<div>
<p>loading...</p>
<button onClick={fetchList}></button>
<p>success</p>
{list.data.map((item) => {
return <p key={item.id}>{item.name + " " + item.types[0].type.name}</p>;
})}
</div>
);
}
Expand Down

0 comments on commit 9ac8d38

Please sign in to comment.