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