Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Toka Ruiz
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.
Here is an example of how the error occurs.
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.
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.
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.
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.
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.
users
variable stores an array, and if it does we return the result of calling the map()
method, otherwise we return null
.