Concise summary of your issue, e.g., "TypeError when calling useEffect in Next.js 14 #81405
-
SummaryI’m experiencing a problem with [brief description of what you're working on, e.g., "a React component using useEffect in a Next.js 14 project"]. The expected behavior is [what should happen], but instead I get [what actually happens, e.g., an error, crash, or incorrect output]. Additional informationFramework/Library/Tool: e.g., Next.js 14, React 18, TailwindCSS
Error message:TypeError: Cannot read properties of undefined (reading 'map') ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
data is likely undefined at first render. So when you do data.map(...), it throws an error. ✅ Solution: tsx Or, with optional chaining: tsx Make sure data is either: Fetched from an API and starts as an empty array: const [data, setData] = useState([]); Or conditionally used only when available. |
Beta Was this translation helpful? Give feedback.
data is likely undefined at first render. So when you do data.map(...), it throws an error.
✅ Solution:
Check if data is defined before calling .map():
tsx
Copy
Edit
useEffect(() => {
if (data) {
setItems(data.map(item => item.name));
}
}, [data]);
Or, with optional chaining:
tsx
Copy
Edit
useEffect(() => {
setItems(data?.map(item => item.name) || []);
}, [data]);
Make sure data is either:
Fetched from an API and starts as an empty array: const [data, setData] = useState([]);
Or conditionally used only when available.