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