How would I go about creating a component using useEffect?
useEffect(() => {
fetch('https://website')
.then((res) => res.json())
.then((data) => {
setData(data)
// Use fetched data to create object "roles"
let cards = roles.map((path) => (
<Box m="sm" pt="xl">
<Card key={path.id} p="lg" radius="md href="#"
onClick={ () => handlePopup(path.role) }>
</Card>
</Box>
));
})
}
return (
<>
{cards} // this doesn't work.
</>
)
Current code is not working. "cards" is not loading, just getting a blank area.
I’m keeping it all in the fetch because the data is dependent and I"m not sure how to split it up. Not sure if there’s a smarter way.
3
Answers
You can map over your state variable outside the
useEffect
If you want to store them in a separate variable, you can set it outside the
useEffect
so that it is accessible.As mentioned in the comments, you also need to set a unique
key
when mapping elements.You should store (
useState
) the raw JS object array (result) from thefetch
call separate from constructing the rendered DOM.A
key
should go on each direct element of theArray.prototype.map
call. In the example below, the<Grid>
wrapper receives this prop.Note: Since the
role
associated with theid
can possibly change over time, theid
or even anindex
may not be unique enough. You could hash the object to receive a truly unique ID, or you can generate a UUID.the best idea in this case is to fetch data outside the useeffect ..then use usestate to create the cards componenet ..use [data] as a variable that useeffect depend on to change or observe