Solve - Cannot read property 'map' of null in React.js

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Toka Ruiz

Solve - Cannot read property 'map' of null #

The "cannot read property 'map' of null" error occurs when we call the map() method on a null value, most often when initializing a state variable to null. To solve the error, initialize the value you're mapping over to an empty array.

cannot read property map of null

Here is an example of how the error occurs.

App.js
import {useState, useEffect} from 'react'; function App() { // ⛔️ State is initialized to `null` const [users, setUsers] = useState(null); useEffect(() => { async function getUsers() { const response = await fetch('https://randomuser.me/api/', { method: 'GET', headers: { accept: 'application/json', }, }); const data = await response.json(); setUsers(data.results); } getUsers(); }, []); console.log(users); return ( <div> {/* ⛔️ users is `null` because API has not responded yet */} {users.map(user => ( <div key={user.id.value}> <h2> Name: {user.name.first} {user.name.last} </h2> </div> ))} </div> ); } export default App;

We declared the users variable and initialized it to null.

When the App function is called it tries to call the Array.map method on a null value, which causes the error.

To solve the error, initialize the value for the users variable to an empty array.

App.js
import {useState, useEffect} from 'react'; function App() { // ✅ State is initialized to `[]` const [users, setUsers] = useState([]); useEffect(() => { async function getUsers() { const response = await fetch('https://randomuser.me/api/', { method: 'GET', headers: { accept: 'application/json', }, }); const data = await response.json(); setUsers(data.results); } getUsers(); }, []); console.log(users); return ( <div> {/* ✅ users is `[]`, until API responds */} {users.map(user => ( <div key={user.id.value}> <h2> Name: {user.name.first} {user.name.last} </h2> </div> ))} </div> ); } export default App;

We provided an empty array as the initial value in our call to the useState method.

This way, the users variable is initially set to an empty array and the map method is called on an empty array instead of a null value.

After our useEffect hook is ran and the remote API responds with the data, we update the state and our component rerenders.

At no point in time of the component's lifecycle is our users variable equal to null and the error won't occur.

If the error persists, console.log the value you are calling the map method on and make sure it is an array.

Check if your API responds with a null value, you might be updating the state variable to null from the API's response, which would cause the error.

You can also conditionally check if the variable is an array before calling the map() method, which would prevent you from getting the error.

App.js
import {useState, useEffect} from 'react'; function App() { const [users, setUsers] = useState([]); useEffect(() => { async function getUsers() { const response = await fetch('https://randomuser.me/api/', { method: 'GET', headers: { accept: 'application/json', }, }); const data = await response.json(); setUsers(data.results); } getUsers(); }, []); console.log(users); return ( <div> {/* ✅ check if array before calling `map()` */} {Array.isArray(users) ? users.map(user => ( <div key={user.id.value}> <h2> Name: {user.name.first} {user.name.last} </h2> </div> )) : null} </div> ); } export default App;

We used a ternary operator, which is very similar to an if/else statement.

We check if the users variable stores an array, and if it does we return the result of calling the map() method, otherwise we return null.
Use the search field on my Home Page to filter through my more than 1,000 articles.