πŸ”§ Error Fixes
Β· 1 min read

Fix: TypeError β€” Cannot destructure property of undefined


TypeError: Cannot destructure property 'name' of undefined

You’re trying to destructure a value that is undefined or null.

Fix 1: Add a default value

// ❌ Crashes if user is undefined
const { name, email } = user;

// βœ… Default to empty object
const { name, email } = user || {};

// βœ… Or with nullish coalescing
const { name, email } = user ?? {};

Fix 2: Default in function parameters

// ❌ Crashes if called with no argument
function greet({ name, age }) {
  console.log(name);
}
greet(); // TypeError!

// βœ… Default parameter
function greet({ name, age } = {}) {
  console.log(name); // undefined, but no crash
}

Fix 3: Check before destructuring

// API response might not have the expected shape
const response = await fetch('/api/user');
const data = await response.json();

// ❌ Assumes data.user exists
const { name, email } = data.user;

// βœ… Guard it
const { name, email } = data.user || {};

// βœ… Or check first
if (data.user) {
  const { name, email } = data.user;
}

Fix 4: React props

// ❌ Parent might not pass user prop
function Profile({ user: { name, email } }) {
  return <p>{name}</p>;
}

// βœ… Destructure safely
function Profile({ user }) {
  if (!user) return null;
  const { name, email } = user;
  return <p>{name}</p>;
}

Common causes

  • API returned a different shape than expected
  • Component rendered before data loaded
  • Accessing a nested property that doesn’t exist
  • Function called without required arguments

See also: Cannot read property of undefined fix | TypeScript cheat sheet

Related: JavaScript Array Methods Cheat Sheet Β· React Interview Questions