I have a list of objects which I want to render in the components return
function.
However, for some reason nothing is rendered at all.
I'm following along this official React guide
const DashboardOffers = () => {
// Get queryset of Offers
let qs_offers = []
fetch('http://127.0.0.1:8000/api/offer/', {
method: 'GET',
headers: {'Content-Type': 'application/json'},
})
.then(res => res.json())
.then(result => {
qs_offers = result
console.log(qs_offers)
})
// Create array of objects to render
const offer_items = qs_offers.map((offer) =>
<div>{offer.identifier}</div>
);
return (
<div>{offer_items}</div>
)
}
export default DashboardOffers
CodePudding user response:
Make it into a hook component,
https://reactjs.org/docs/hooks-overview.html
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes. (We don’t recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you’d like.)
const DashboardOffers = () => {
const [offers, setOffers] = useState([]);
// Get queryset of Offers
useEffect(() => {
let qs_offers = []; // possibly not needed.
fetch("http://127.0.0.1:8000/api/offer/", {
method: "GET",
headers: { "Content-Type": "application/json" },
})
.then((res) => res.json())
.then((result) => {
setOffers([...offers, result])
console.log(qs_offers);
});
}, [offers]); // optional
// Create array of objects to render
const offer_items = qs_offers.map((offer) => <div>{offer.identifier}</div>);
return <div>{offer_items}</div>;
};
export default DashboardOffers;