'Uncaught TypeError: Cannot read properties of undefined (reading 'map') - Firestore API
I am using react-admin to fetch data from a Firestore API in the following format:
{
"documents": [
{
"name": "",
"fields": {
"teacher": {
"stringValue": ""
},
"slot": {
"stringValue": ""
},
"student_name": {
"stringValue": ""
}
},
"createTime": "2022-03-27T09:49:24.044423Z",
"updateTime": "2022-03-29T13:50:41.264007Z"
},
{
"name": "",
"fields": {
"teacher": {
"stringValue": ""
},
"slot": {
"stringValue": ""
},
"student_name": {
"stringValue": ""
}
},
"createTime": "2022-03-27T09:49:24.044423Z",
"updateTime": "2022-03-29T13:50:41.264007Z"
},
{
"name": "",
"fields": {
"teacher": {
"stringValue": ""
},
"slot": {
"stringValue": ""
},
"student_name": {
"stringValue": ""
}
},
"createTime": "2022-03-27T09:49:24.044423Z",
"updateTime": "2022-03-29T13:50:41.264007Z"
}
]
}
However, when I try to extract certain fields from the data like this,
const List = () => {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
// Note: the empty deps array [] means
// this useEffect will run once
// similar to componentDidMount()
useEffect(() => {
fetch("MY API URL")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name}
</li>
))}
</ul>
);
}
I am getting the following error : Uncaught TypeError: Cannot read properties of undefined (reading 'map')
I found a similar answers including this one here : TypeError: Cannot read properties of undefined (reading 'map') Table.render
But was still unable to figure it out. Any help would be great, thanks!
Solution 1:[1]
You can try Optional Chaining(?.) at your items.
{items?.map(item => (
<li key={item.id}>
{item.name}
</li>
))}
This should prevent the error.
Another important thing is that result you get back from your fetch request might probably be undefined and would raise the TypeError.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Osamu Renji |
