Goal:
Use another api get url with different json data and then display it in the front end.
Problem:
The data is located in the map "results" with is not the main root (https://pokeapi.co/api/v2/pokemon).
Due to that I was not enable to retrieve the data compare to to the previous url (https://jsonplaceholder.typicode.com/users)
The question is:
How do I retrieve the data when the data is located in the map "results"
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
{
"count": 1351,
"next": "https://pokeapi.co/api/v2/pokemon?offset=20&limit=20",
"previous": null,
"results": [
{
"name": "bulbasaur",
"url": "https://pokeapi.co/api/v2/pokemon/1/"
},
{
"name": "ivysaur",
"url": "https://pokeapi.co/api/v2/pokemon/2/"
},
{
Other:
Newbie in react TS
------------------------
App.tsx
import { useEffect, useState } from 'react';
import { fetchUsersWithErrorHandling, type User } from './apiClient';
function App() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const getUsers = async () => {
try {
const response = await fetchUsersWithErrorHandling();
if (response === null) {
setError('Failed to fetch users.');
return;
}
setUsers(response);
console.log('Fetched users:', response);
} catch (err) {
setError('Failed to fetch users.');
} finally {
setLoading(false);
}
};
getUsers();
}, []);
if (loading) return Loading...
;
if (error) return {error}
;
return (
Count: {users.length}
{users.map((u) => (
-
{u.name}: {u.name}
))}
);
}
export default App;
apiClient.ts
import axios, { type AxiosResponse } from 'axios';
const apiClient = axios.create({
baseURL: 'https://pokeapi.co',
headers: {
'Content-Type': 'application/json',
},
});
// Define a generic API function
export const apiRequest = async (
url: string,
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
data?: any
): Promise => {
const response: AxiosResponse = await apiClient({
method,
url,
data,
});
return response.data;
};
export const fetchUsersWithErrorHandling =
async (): Promise => {
try {
return await apiRequest('/api/v2/pokemon', 'GET');
} catch (error) {
console.error('Failed to fetch users:', error);
return null;
}
};
export interface User {
name: string;
url: string;
}
type UserListResponse = User[];
export const fetchUsers = async (): Promise => {
return await apiRequest('/users', 'GET');
};
interface CreateUserRequest {
name: string;
username: string;
email: string;
}
interface CreateUserResponse {
slot: number;
name: string;
email: string;
}
export const createUser = async (
userData: CreateUserRequest
): Promise => {
return await apiRequest('/users', 'POST', userData);
};