I trying to Fetch data from Random user API, but I get the following error:
"Objects are not valid as a React child (found: object with keys {title, first, last}). If you meant to render a collection of children, use an array instead."
Here my code so far:
import "./styles.css";
import React, { useState, useEffect } from "react";
import { User } from "../interfaces/users";
import axios, { AxiosResponse } from "axios";
export default function App() {
const [randomUsers, setRandomUsers] = useState<User[]>([]);
useEffect(() => {
axios
.get<User[]>("https://randomuser.me/api/?results=20")
.then((response: AxiosResponse) => {
setRandomUsers(response.data.results);
});
}, []);
return (
<div className="App">
<h1>Names from random user API</h1>
<ul>
{randomUsers.map((user, key) => (
<li key={key}>{user.name}</li>
))}
</ul>
</div>
);
}
I don't understand why I can't map randomUsers
Here the code sandbox:
Any help will be appreciated
you are facing this error because names is an object so try this
<li key={key}>{user.name.first}</li>