This error occurs when you try to call .map() on a variable that is undefined instead of an array. Common scenarios:
// Before (crashes)
items.map(item => <div>{item.name}</div>)
// After (safe)
items?.map(item => <div>{item.name}</div>)
// Using nullish coalescing
(items ?? []).map(item => <div>{item.name}</div>)
// Using logical OR
(items || []).map(item => <div>{item.name}</div>)
// In destructuring
const { items = [] } = data;
function MyComponent({ items }) {
if (!items) {
return <div>Loading...</div>;
}
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}
// Before
const [items, setItems] = useState();
// After
const [items, setItems] = useState([]);
// Verify the data path is correct
fetch('/api/data')
.then(res => res.json())
.then(data => {
// Debug: check actual structure
console.log(data);
// Maybe it's data.items, not data
setItems(data.items || []);
});
[] in stateinterface Props {
items: Item[]; // Required array
// or
items?: Item[]; // Optional - forces you to handle undefined
}
@typescript-eslint/no-unsafe-callSign in to post your answer