In my Code Sandbox I am working with the SpaceX API to fetch some data, and I want to be able to map through all the items. But at the moment I am getting an error saying that .map in not a function.
import React from "react";
import { useState, useEffect } from "react";
import { Container } from "react-bootstrap";
import Information from "./Information";
import axios from "axios";
import "./styles.css";
export default function App() {
const [items, setItems] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchItems = async () => {
const result = await axios(
"https://api.spacexdata.com/v4/launches/latest"
);
setItems(result.data);
console.log(result.data);
setIsLoading(false);
};
fetchItems();
}, []);
return (
<div className="header">
<Container>
{items.map((item) => {
return (
<Information key={item.id} item={item} isLoading={isLoading} />
);
})}
</Container>
</div>
);
}
Any reason as to what can cause this?
map
is an array method, you can’t map
an object.
So I changed some stuff around like these
const [items, setItems] = useState({});
and
<Container>
{Object.keys(items).map((item, i) => (
<Information key={i} item={item}/>
))}
</Container>
It seems to map through everything but does not display the result in my Information
component
Right, well now, before the request completes, items
is an empty array. And when it does return, the object is a huge nested thing, how does Information
work?
With objects, you can specify exactly what you want by selecting the properties you want. Blindly turning it into an array and mapping over the properties is likely to not give you results you want. map
is for a list of items of the same type, not objects
My Information
consists of this
import React from "react";
export default function Information({ isLoading, item }) {
return isLoading ? (
<h1>Loading</h1>
) : (
<section>
<h1>{item.details}</h1>
</section>
);
}
Basically there is all this stuff and I want to be able to retrieve information like details
Normall something like:
export default function App() {
const [data, setData] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(false);
const [error, setError] = React.useState(null);
useEffect(() => {
const fetchItems = async () => {
setError(null);
setIsLoading(true);
try {
const result = await axios("https://api.spacexdata.com/v4/launches/latest");
setData(result.data);
} catch(err) {
setError(err) // do something with this
} finally {
setIsLoading(false);
}
};
fetchItems();
}, []);
return (
<div className="header">
<Container>
{ isLoading ? <LoadingComponent />
: error ? <ErrorComponent />
: <Information details={data.details} /> }
</Container>
</div>
);
}
3 Likes