The Exact Error
TypeError: Cannot convert undefined or null to object
Or:
TypeError: Cannot convert undefined to object (Object.keys called on non-object)
TypeError: null is not an object (evaluating 'Object.keys(data)')
Quick summary:
Object.keys(),Object.values(), orObject.entries()was called withnullorundefined. These methods require an actual object. The data either hasn't loaded yet, the API returned null, or the object was accessed at the wrong nesting level.
Why This Error Happens
Object.keys(x) converts x to an object internally. The ECMAScript ToObject() operation throws a TypeError for null and undefined.
Five root causes:
1. Async timing โ Calling Object.keys(data) before an API response arrives. Initial state is null.
2. API returning null โ Backend returns null instead of {} when a record doesn't exist.
3. Wrong property access โ Object.keys(response.data) when the actual data is at response.body.data.
4. Optional chaining result โ Object.keys(user?.preferences) โ if user?.preferences returns undefined, this throws.
5. Destructuring with missing keys โ const { settings } = apiResponse โ if settings doesn't exist, it's undefined.
Step-by-Step Diagnosis
Step 1 โ Log the value before the call
console.log('data value:', data);
console.log('data type:', typeof data);
Object.keys(data); // Error here
Step 2 โ Check initial state
const [userData, setUserData] = useState(null); // null initial state!
Object.keys(userData) // Throws on first render
Step 3 โ Check optional chaining results
const prefs = user?.preferences; // undefined if user is null
Object.keys(prefs); // TypeError!