Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

Cannot read map of undefined in React - Fix (2026) | Tutorials Logic

What is This Error?

The error "Cannot read properties of undefined (reading 'map')" is extremely common in React. It occurs when you try to call .map() on a variable that is undefined or null — usually because async data hasn't loaded yet, or an API returned an unexpected shape.

Common Causes

  • State initialized as undefined instead of an empty array
  • API data not loaded yet when component first renders
  • API response has a different shape than expected
  • Prop not passed to component (undefined by default)
  • Accessing a nested property that doesn't exist

Quick Fix (TL;DR)

Quick Solution
// ❌ Problem
const [users, setUsers] = useState(); // undefined!
return users.map(u => 

{u.name}

); // Error! // ✅ Solution 1: Initialize with empty array const [users, setUsers] = useState([]); // ✅ Solution 2: Optional chaining return users?.map(u =>

{u.name}

); // ✅ Solution 3: Fallback return (users || []).map(u =>

{u.name}

);

Common Scenarios & Solutions

Scenario 1: State Not Initialized as Array

Problem
function ProductList() {
  const [products, setProducts] = useState(); // ❌ undefined!

  useEffect(() => {
    fetch('/api/products')
      .then(r => r.json())
      .then(setProducts);
  }, []);

  return products.map(p => 
{p.name}
); // Error on first render! }
Solution
function ProductList() {
  const [products, setProducts] = useState([]); // ✅ Empty array default
  const [loading, setLoading] = useState(true);

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

  if (loading) return 

Loading...

; return products.map(p =>
{p.name}
); }

Scenario 2: API Returns Nested Data

Problem
// API returns: { data: { users: [...] } }
useEffect(() => {
  fetch('/api/users')
    .then(r => r.json())
    .then(setUsers); // ❌ Sets users to { data: { users: [...] } }
}, []);

return users.map(u => 

{u.name}

); // Error! users is an object
Solution
useEffect(() => {
  fetch('/api/users')
    .then(r => r.json())
    .then(response => {
      setUsers(response.data.users); // ✅ Extract the array
    });
}, []);

// Or with optional chaining as safety net
return (users ?? []).map(u => 

{u.name}

);

Scenario 3: Prop Not Passed

Problem
function List({ items }) {
  return items.map(item => 
  • {item}
  • ); // Error if items not passed! } // Usage — forgot to pass items // items is undefined!
    Solution
    // ✅ Default prop value
    function List({ items = [] }) {
      return items.map(item => 
  • {item}
  • ); } // ✅ Or with PropTypes import PropTypes from 'prop-types'; List.defaultProps = { items: [] }; List.propTypes = { items: PropTypes.array };

    Scenario 4: Conditional Rendering with Loading State

    Solution
    function DataList() {
      const [data, setData] = useState(null);
      const [loading, setLoading] = useState(true);
      const [error, setError] = useState(null);
    
      useEffect(() => {
        fetch('/api/data')
          .then(r => r.json())
          .then(setData)
          .catch(setError)
          .finally(() => setLoading(false));
      }, []);
    
      if (loading) return 

    Loading...

    ; if (error) return

    Error: {error.message}

    ; if (!data || !Array.isArray(data)) return

    No data

    ; return (
      {data.map(item =>
    • {item.name}
    • )}
    ); }

    Best Practices to Avoid This Error

    • Always initialize array state with [] - Never leave it as undefined
    • Use loading states - Show a spinner while data is being fetched
    • Validate API response shape - Log the response to verify its structure
    • Use default props - Provide fallback values for array props
    • Use optional chaining - data?.map() returns undefined instead of throwing
    • Check Array.isArray() - Verify data is actually an array before mapping
    • Handle errors gracefully - Show error messages when fetch fails

    Related Errors

    Key Takeaways
    • Always initialize array state with [] not undefined
    • Data from APIs is undefined on the first render — always show a loading state
    • Use optional chaining (data?.map()) as a safety net
    • Verify the API response shape matches what you expect before mapping
    • Use default props to provide fallback empty arrays for array props
    • Check Array.isArray(data) before calling .map() for extra safety

    Frequently Asked Questions


    Ready to Level Up Your Skills?

    Explore 500+ free tutorials across 20+ languages and frameworks.