Stop putting fetch in components
Here’s what most beginners do — scatterfetch() calls throughout their components:
The companion repo already uses an API client file (
frontend/src/api/users.ts) with this pattern. In this lesson, we stay in JavaScript and then add an optional shared client.js helper as a teaching step to reduce repetition further.The API client pattern
Create a dedicated file for each resource’s API calls:getUsers() and gets data back.
File structure
Reducing duplication with a helper
Notice how every function repeats the same pattern: fetch, check response, parse JSON. Extract a helper:The
apiClient helper reads the FastAPI error message (error.detail) when available. This means your backend’s validation errors (“Email is required”) show up directly in the frontend — no extra work needed.Why this pattern matters
This isn’t over-engineering — it’s the minimum level of organization you need once your app has more than 2-3 API calls.
Using the API client in components
What’s next?
Your API calls are organized. But how do you make sure the data your frontend sends matches what your backend expects? Let’s talk about type safety.Type safety
Ensure your frontend and backend agree on data shapes