Skip to content
Discussion options

You must be logged in to vote

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.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by MohammedMohtaseb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
2 participants