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?