Back to More
Bug of the Week

Cannot read properties of undefined (reading 'map')

One bug. Why it happens. How to fix it. What to never forget.

JavaScriptReactDifficulty: Beginner
TypeError: Cannot read properties of undefined (reading 'map')

You've seen this. You've stared at it at 1am wondering why your perfectly written .map() is somehow broken.

What's Actually Happening

JavaScript is trying to call .map() on a value that is undefined. The .map() method only works on arrays. If the variable you're calling it on hasn't loaded yet, or came back as undefined from an API, JavaScript throws this error.

The Code That Breaks

function ProductList() {
  const [products, setProducts] = useState();  // ← undefined by default

  useEffect(() => {
    fetch("/api/products")
      .then(res => res.json())
      .then(data => setProducts(data));
  }, []);

  return (
    <div>
      {products.map(p => (   // ← ERROR on first render
        <p key={p.id}>{p.name}</p>
      ))}
    </div>
  );
}

Why it breaks: On the very first render, products is undefined because the API call hasn't finished yet.

The Fix

Option 1 — Initialize with an empty array

const [products, setProducts] = useState([]);  // ✅ empty array, not undefined

Option 2 — Guard with optional chaining

{products?.map(p => (
  <p key={p.id}>{p.name}</p>
))}

Option 3 — Loading state (best practice)

function ProductList() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/products")
      .then(res => res.json())
      .then(data => {
        setProducts(data);
        setLoading(false);
      });
  }, []);

  if (loading) return <p>Loading...</p>;

  return (
    <div>
      {products.map(p => (
        <p key={p.id}>{p.name}</p>
      ))}
    </div>
  );
}

Prevention Rule

Never initialize state that will be an array as anything other than [].

const [items, setItems] = useState([]);
const [user, setUser] = useState(null);
const [count, setCount] = useState(0);