I need help (Api calls in React Js Hooks) Why is this nort working? I need to call the values from that API
import React, { useEffect, useState } from 'react';
function Customers() {
const [customers, setCustomers] = useState(null);
useEffect(() => {
fetch('https://reactstarter-app.herokuapp.com/api/customers') **API CALLS**
.then(res => res.json())
.then(customers => setCustomers(customers))
}, [])
return (
<div>
<h2>Customers</h2>
<ul>
{customers.map((customer) => {
return <li key={customer.id}>{customer.firstName} {customer.lastName}</li>
})}
</ul>
</div>
);
}
export default Customers;
CodePudding user response:
Maybe it isn't a solution, but I cannot paste code to comment, so I have to post an answer:
function Customers() {
// this is where you declare the "customers" const
const [customers, setCustomers] = useState(null);
useEffect(() => {
fetch('https://reactstarter-app.herokuapp.com/api/customers') **API CALLS**
.then(res => res.json())
// this is where you should change the "customers" to "data"
// because of the variable name conflict
.then(data => setCustomers(data))
}, [])
CodePudding user response:
It looks like you're trying to map through a null state and probably getting an error, use conditional rendering to avoid the error and render the customers after the api request:
import React, { useEffect, useState } from 'react';
function Customers() {
const [customers, setCustomers] = useState(null);
useEffect(() => {
fetch('https://reactstarter-app.herokuapp.com/api/customers') **API CALLS**
.then(res => res.json())
.then(customers => setCustomers(customers))
}, [])
return (
<div>
<h2>Customers</h2>
{!customers ? <h2>Loading customers...</h2> :
<ul>
{customers.map((customer) => {
return <li key={customer.id}>{customer.firstName} {customer.lastName}</li>
})}
</ul>}
</div>
);
}
export default Customers;