Why do I need an empty dependency array for the fetch?
So the effect runs only once when the component mounts. Without a dependency array, it runs on every render, causing an infinite loop of fetches. The empty array signals that the effect has no dependencies and should run once.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Using the Swiggy API With useEffect: A Step-by-Step Example
Declare state for data, loading, and error. Inside useEffect with an empty dependency array, define an async function that calls the endpoint, parse the response, store the data, and handle errors. Call the function immediately so it runs on mount.
Use a cleanup flag. Declare a variable that tracks whether the component is still mounted, set it to false in the cleanup function, and only update state if it is still true. This avoids the warning about updating state on an unmounted component.
Read the actual response before rendering. The data is often nested inside an object, so extract the restaurant array from the correct field before calling map on it. Assuming it is a top-level array causes 'map is not a function' errors.
Still have questions?
Browse all our FAQs or reach out to our support team
