Error : Cannot read property 'map' of undefined
First of all, set more safe initial data:
getInitialState : function() {
return {data: {comments:[]}};
},
And ensure your ajax data.
It should work if you follow above two instructions like Demo.
Updated: you can just wrap the .map block with conditional statement.
if (this.props.data) {
var commentNodes = this.props.data.map(function (comment){
return (
<div>
<h1>{comment.author}</h1>
</div>
);
});
}
TypeError: Cannot read properties of undefined (reading 'map') even though useState() is initialized with array
You're probably just off by just a few ms in the timing of the API call and the rendering. A good practice is to check for the existence of the array you're mapping before trying to render any JSX. Set your initial state to null and do optional chaining on your map line.
Refactor your component something like this:
import { useState, useEffect } from "react/cjs/react.development";
import * as constants from "../../../../constants";
export default function Keywords(props) {
const [movieKeywords, setMovieKeywords] = useState();
useEffect(() => {
const fetchKeywords = async () => {
const data = await fetch(
`${constants.TMDB_BASE_PATH}movie/${props.id}/keywords?api_key=${constants.API_KEY}`
);
const jsonData = await data.json();
setMovieKeywords(jsonData.keywords);
console.log("xdd");
};
fetchKeywords();
}, []);
return (
<div className="flex flex-wrap">
{movieKeywords?.map((keyword) => {
return (
<div className="border font-oxygen m-1 rounded-xl cursor-pointer text-xs text-gray-300 px-2 py-1">
<p>{keyword.name}</p>
</div>
);
})}
</div>
);
}
Notice the movieKeywords?.map
, this will not execute map until movieKeywords
is not null, meaning it will wait until the fetch resolves and your state is set.
TypeError: Cannot read property 'map' of undefined React
Your items
object is undefined at the start. Just add a null check:
const ListGroup = props => {
const {items,textProperty,valueProperty} = props;
return (
<ul className="list-group">
{items && items.map(item =>(
<li key={item[valueProperty]} className="list-group-item">
{item[textProperty]}
</li>
))}
</ul>
);
}
Cannot read properties of undefined (reading 'map') in React
In your App.js change your fetchProduct
function as follows:
const fetchProduct = async = {
const products = await commerce.products.list();
setProducts(products.data);
}
and then in your Products.js map over the products instead of products.data,
{products.map((product) => (
<Grid item key={product.id} xs={12} sm={6} md={4} lg={3}>
<Product product={product} />
</Grid>
))}
EXPLANATION:
The initial State of products is an empty array, which is passed down to the products component, where you tried products.data.map()
but products is an array (initially) and there is no data property on arrays, so it threw error.
There are several ways you can get around this, but if you are only using the products data from the response then you can go with the above approach, where you map over the products
not products.data
and setProducts()
with the products array instead of products object.
Fetching data using props - Cannot read properties of undefined (reading 'map')
The issue you have here seems to be that you are trying to access an object credits
inside credits
where you can already access cast
.
{loading ? (
"Loading"
) : credits && credits.cast ? (
credits.cast.map((castMember) => <h1>{castMember.id}</h1>)
) : (
<div>{"Error fetching credits"}</div>
)}
works for me.
I've added an extra check for credits
and credits.cast
just to avoid trying to access that object when undefined. I've also changed <h1>{castMember}</h1>
to <h1>{castMember.id}</h1>
because I then got an error that the object wasn't a valid react child, so just printing out the id here to show that you can now access the properties of castMember
.
Here's the updated sandbox:
https://codesandbox.io/s/tmdb-credits-forked-xwqp1b?file=/src/Components/Credits/Credits.js:428-630
React mapping ERROR: Cannot read properties of undefined (reading 'toLocaleString')
You're using the wrong object keys in your expenseData
object in the ExpenseForm
component. And so the date
will "always" be undefined
thus failed during the date conversion in your ExpenseDate
component. To fix this, you just need to supply the correct object:
From this:
const expenseData = {
inputValue: enteredValue,
inputAmount: enteredAmount,
inputDate: new Date(enteredDate),
};
To this:
const expenseData = {
id: "e5", // You will need to figure out a way to create a dynamic ID here :)
title: enteredValue,
amount: enteredAmount,
date: new Date(enteredDate),
};
Related Topics
Jquery Draggable with Zoom Problem
Getting the Values of All the CSS Properties of a Selected Element in Selenium
Using JavaScript to Mark a Link as Visited
Interrupting/Stop a CSS3 Transition on the Actual Position/State
R Shiny Datatable Selected Row Color
Wait for Background Images in CSS to Be Fully Loaded
How to Use Materialize-CSS with Angular
Remove/Reset Inherited CSS from an Element
Div Square, Width Size Based on 100% Height
Using Queryselectorall(). Is the Result Returned by the Method Ordered
Why Browser Is Returning Empty String on Style.Height ? How to Get Actual Height of an Element
Jquery How to Apply CSS to Selected Text
Mime Type Error with Express.Static and CSS Files
Filling Empty Cells in CSS Grid Layout
Inherited CSS Values via JavaScript
Changing Background Color of Div on Scroll
Mutationobserver: New Value in the Format of 'Oldvalue'
Javascript: Get Deep Value from Object by Passing Path to It as String