I had an issue where my feature wasn't rendering because I don't think React understood the state was changing. After changing the forEach()
to map()
, the feature rendered as expected.
Feature will take user's subscriptions from an API then render as list. This is the final working version.
...
export default function MyComp() {
const [userSubIds, setUserSubIds] = useState()
useEffect(() => {
getSubs().then(p => setUserSubIds(p))
}, [])
return (
<>
{
userSubIds?.map(subId => {
<ListItem>
{subId.data}
</ListItem>
})
}
</>
)
Previously I had used forEach()
. This did not return any error nor any feature on the web page.
...
userSubIds?.forEach(subId => {
<ListItem>
{subId.data}
</ListItem>
})
...
From reading the docs, forEach()
always returns undefined
and map()
returns a new array. But what I'm missing in knowledge is why this matters for rendering?
This is because, your loop has to return elements. Those elements will go into your tags and thus it will be rendered.
Now, map
returns an array of the same size with the modified elements.
forEach
does not return anything. It is just traversing the array. It does not give react the elements that it needs.
<>
{
userSubIds?.map(subId =>
<ListItem>
{subId.data}
</ListItem>
)
}
<>
// This has returned elements like this
<ListItem> some data </ListItem>
<ListItem> some data </ListItem>
<ListItem> some data </ListItem>
...
However, forEach
has not returned any data.
userSubIds?.forEach(subId =>
<ListItem>
{subId.data}
</ListItem>
})
// This has returned nothing.