Can anyone see where I mess up this fetch? Error message; TypeError: Cannot read properties of undefined (reading 'map')
This is how the data looks like
Happy for any help!
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
export const PressReleaseList = () => {
const [pressReleases, setPressReleases] = useState([null]);
useEffect(() => {
(async function () {
try {
const res = await fetch(
'https://feed.mfn.se/v1/feed/3XXXXX.json'
);
const json = await res.json();
setPressReleases(json.items);
} catch (e) {
console.error(e);
}
})();
}, []);
return (
<Main>
{pressReleases.items.map((item) => (
<TextCell key={item.news_id}>
<CategoryText>{item.title}</CategoryText>
</TextCell>
))}
;
</Main>
);
CodePudding user response:
Double check your key={item.news_id}
. Looks like item
is missing an 's,' should be key={items.news_id}
based off your screenshot.
CodePudding user response:
Initially when your loop runs (before the Ajax call completes), it's running the .map
on an array whose only child is a null
(derived from const [pressReleases, setPressReleases] = useState([null]);
).
Within your loop, when you're calling item.news_id
you're essentially doing null.news_id
thus your app crashes.
Change your useState to the following:
const [pressReleases, setPressReleases] = useState([]);
This will ensure you have an empty array, thus you don't ever loop until you have data.
CodePudding user response:
You are trying to access twice to items. Try setting setPressReleases only with the json variable or apply the map function to pressReleases directly.
And given the error code in your comment, we can see that you are trying to render a list (item.subjects
) in a JSX Element instead of primitives.