Are you a react developer? If yes, it’s not too surprising that you get an error Cannot read property ‘map’ of undefined. So, if you haven’t had a good solution for this issue, the blog today will be helpful for you. Now, let’s check it out!
Cannot read property ‘map’ of undefined – What’s going on?
In order to help you understand the issue in a clear and simple way, let’s take a look at the following example.
We will have the code block:
// Just a data fetching function
const fetchURL = "https://jsonplaceholder.typicode.com/todos/";
const getItems = () => fetch(fetchURL).then(res => res.json());
function App() {
const [items, setItems] = useState();
useEffect(() => {
getItems().then(data => setItems(data));
}, []);
return (
<div>
{items.map(item => (
<div key={item.id}>{item.title}</div>
))}
</div>
);
}
There is a component managing the state of items and it also has an effect in which we run an asynchronous operation. Normally, getItems will return the data which we want from the server. After that, we will can it with the received data as the items. This component iterates over it with the .map and returns a react element for each item. If nothing happens, the error Cannot read property ‘map’ of undefined will appear.
As you can see, in the example above, we have the items variable:
const [items, setItems] = useState();
We fill out it with the data that is returned from the server:
useEffect(() => {
getItems().then(data => setItems(data));
}, []);
In this case, react invokes the component. React see the usestate
call, then return [undefined, fn]
. After that, react continues to evaluate the return statement with the items.map(...)
line, it runs undedined.map(...)
. Obviously, this is a Javascript error.
So, how about the useEffect
call? By default, react runs all effects after the render is committed to the screen. Thus, we get the first render without the data.
Now, we will find out together to know which is the best solution for this trouble!
How to solve the error Cannot read property ‘map’ of undefined
Initial value
The first solution to this problem is offering the variable a default initial value, for instance:
const [items, setItems] = useState([]);
So, when react runs the useState([])
call, it will return: [[], fn]
In other words, in the first render of the component, react will understand that the items as an empty array. Therefore, it will run [].map(...)
instead of undefined.map(...)
.
Conditional rendering
The next useful method to tackle the error Cannot read property ‘map’ of undefined is that we conditionally render the items. Simply put, if
we have items so render them, else
don’t render or render something else. For instance:
function App() {
const [items, setItems] = useState();
useEffect(() => {
getItems().then(data => setItems(data));
}, []);
let itemsToRender;
if (items) {
itemsToRender = items.map(item => {
return <div key={item.id}>{item.title}</div>;
});
} else {
itemsToRender = "Loading...";
}
return <div>{itemsToRender}</div>;
}
Inline conditional rendering
Another solution that is related to conditionally rendering something in react is to use the &&
logical operator. For example:
function App() {
const [items, setItems] = useState();
useEffect(() => {
getItems().then(data => setItems(data));
}, []);
return (
<div>
{items && items.map(item => {
return <div key={item.id}>{item.title}</div>;
})}
</div>
);
}
This method can deal with the error Cannot read property ‘map’ of undefined since true && expression will always evaluate the expression and false && will evaluate false. That means if the condition is true, the element that is after && will appear in the output. Conversely, if the element is false, the react will ignore it.
Closing thoughts
In conclusion, whenever you face the error Cannot read property ‘map’ of undefined, you can try to give the variable an initial value. Besides, using conditionally rendering or inline conditional rendering may be useful for you to deal with the issue. We hope that the blog today is helpful for you to address the error. If you have more ideas related to this error, don’t hesitate to leave your comment below.
Last but not least, we are providing a lot of mobile-friendly and eye-catching Free WordPress Themes and Joomla 4 Templates. Therefore, if you desire to renew your site appearance, don’t forget to visit our site and get the best one for your site. Thanks for your reading and have a good day.
- How to place menu items in helix joomla 5 ? - December 14, 2024
- How to reduce the size of helix 2 layout ? - December 14, 2024
- What’s J4 starter template and how to use it - December 3, 2024
Recent Comments