How do I fetch data from an API in React?
Create state for the data, a loading flag, and an error. Fetch inside useEffect with an empty dependency array, parse the response, store the data in state, and set loading to false in a finally block. Render based on the three states.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in How to Fetch Restaurant Data From an API in React
Because fetching is a side effect, and useEffect is where side effects belong in React. With an empty dependency array, the fetch runs once when the component mounts, which is usually what you want for initial data loading.
Three: loading, error, and success. Show a spinner while loading, an error message if the fetch fails, and the data once it arrives. Skipping any of these leads to a UI that looks broken when things go wrong.
Check if the response is ok, and wrap the fetch in try/catch. On failure, set an error state and render an error message. Always set loading to false in a finally block so the spinner stops even on failure.
Still have questions?
Browse all our FAQs or reach out to our support team
