Data Fetching for Single-Page Apps
martinfowler.com
martinfowler.com
The shown implementation is naive and prone to bugs, for example a race condition. If this id is rapidly changed (say from 1->2), and the first request arrives last, you think you are looking at user 2 but you've loaded data for user 1.
const [user, setUser] = useState<User | undefined>();
useEffect(() => {
const fetchUser = async () => {
const response = await fetch(`/api/users/${id}`);
const jsonData = await response.json();
setUser(jsonData);
};
fetchUser();
}, [id]);
If you don't know what you're doing, use Tanstack Query libs or read a better article.- https://tanstack.com/query/latest
- https://maxrozen.com/race-conditions-fetching-data-react-wit...
better immediately hide user1 and show a loading button and use rxjs's switchmap
Also your proposed solution involves a lot more moving pieces.
Sounds like a 20/80 solution.
Hiding the elements/div would prevent the user from clicking that button.
I don't see how it is 20/80.
Switchmap is just a different way of doing things, and hiding the deiv instead of blocking doesn't add really add more effort as well. So I don't see how it's a lot of effort while also missing a lot of the desired features?
If you're going to start adding logic to hide other elements conditionaly it's prone to become spaguetti. And how would that scale code-wise?
Might as well dim the screen and show a loading spinner to convey to the user that they should wait, a fraction of a second on average.
Remember this is in the context of a LOB app. Not facbook.
Just show a loading spinner from an axios callback and be done with it. It's so fast anyway.
Other libs listen to these events to, for example, show loading spinner on request.
this is a trivial task, it's only going to spaghetti if you go out of your way to make that happen
Or in case some fool on your dev team calls the events to automate (or for other reasons trigger) something that wasn't intended to be called that way, of course, though once you start defending against iffy practise from within you are fighting a battle you are going to lose!
In case you trigger a native fetch, you've got no way to cancel the call due to the missing cleanup fn.
Wrong. That's just like, your opinion.
The best time to kick off external calls is during first render, not after the component is mounted and React has gotten around to calling your useEffect callback.
useMemo can be a part of the solution along with useRef and useEffect cleanup(remember it's essentially to the unmount lifecycle hook as well).
But triggering an api request having side effects is 100% incorrect.
awful but works.
React hooks caused this because by default there’s no sensible place to fetch data.
So unless you know ahead of time, any complex single page ends up with complex and hard to track network requests.
The solution is really simple: pull data out of the view layer and make it a first class citizen.
—
An exercise: imagine you’re building a tui instead of a web app, but you’re forced to use the exact same code for app state and data fetching… what would that code look like?
I don't understand what it means to "pull data out of the view layer and make it a first class citizen". If you're writing a React app, you are building a UI and will need to handle data in your view layer somewhere. You either hand-off that works to a library like Tanstack Query or you manage it yourself.
UI = f(state)
The problems come when you modify state in response to rendering the UI. This seems deceptively natural (and in fact seems encouraged by on-line tutorials), but leads to "spaghetti fetching" when composing components together - it creates a "feedback loop" that modifies state just because some component happens to mount, which can then modify state further, then cause further mounting/fetching etc...
A better approach is to treat fetching as an explicit state change. If user clicks on a button, you do the fetch and modify the state. If that causes some components to be mounted - so be it, but does not cascade any further.
Yeah don't do that. Rendering shouldn't have such side-effects. Navigation might, but that's not rendering. Is it a common mistake with React?
On the other hand, I can also see some drawbacks:
1. This goes against the idea of fetching data close to where it's used, basically promoting modularization.
2. From the POV of the children, you have to backtrack where their data are coming from.
3. If components always use the same data, you have to duplicate fetching their data everywhere you want to use them.
4. You can't partially show children, but have to wait for everyone to have their data before rendering them.
I feel like there are trade-offs to be made here.It prevents the umpteenth reinvention of an incomplete fetch state machine, which is probably the number one most consistent frontend bug I encounter.
Instead of talking high-level framework agnostic code design and the multitudes of ways to fetch data (route based, state stores, authentication hooks, subscriptions, model composition , to name a few ); author goes deep into outdated React anti-patterns.
Everyone who has commented on this is spot on.
If you want to have an after routing/rendering loading feedback, such as skeleton or so, you still can do it, but it will be opt-in, not an after thought of savage data fetching and rendering that really might happens as the application gains features and diverts from the simple POC patterns.
Proper data fetching and rendering cannot happen without a router. Remix solved this with their updated react-router, I know that this router has a bad rep with breaking changes, but they finally landed the implementation that neatly cover most if not all the use cases for routing with dynamic code imports and data fetching.
Why is that desirable? I see it more like a limitation of server-rendered web apps. Many times you can show useful UI before actual data is fully loaded (i.e. search / filter controls or basic data you already have).
Certainly, cascading fetching is undesirable and you should know what data you need to fetch and start the requests as soon as possible, but not necessarily before the route transition occurs.
It can be done, yeah, but it has to be handled very carefully because it runs the risk of causing more issues than it solves. I can't count the number of times I've used the AWS Console, loaded a page, clicked on a control, only to find that the data that was loaded a few milliseconds before caused the elements on the page to shift so now I clicked on a completely different button, started the process to load a new page and now have to reload the old one and wait for the entire page to finish loading or risk a misclick again.
It's not an intrinsic limitation of server-rendered apps. Apollo solves this https://www.apollographql.com/docs/react/performance/server-... as do many other data-fetching libraries.
Got any suggestions for where to look if I'd like to learn more about what that means exactly?
They combine react router pre-fetching with tanstack query.
For example I interact with a medical app. When you open a patient card, there's lots of data getting requested. It halts the new context opening for a long time, even though you need only a fragment of this data. I'd love it if it didn't wait and instead opened the basic information with placeholder blocks that get loaded as the data comes in. You really don't need all the old visits loaded in a collapsed tree that you're not going to use. This would save significant amount of time ever day.
I've managed a database of local rescuers veterans, including their full PII, illnesses, statuses, family, etc. Even the floor they lived on and how much they drink was in there. It was one form per person with all the data, opened in an instant in a DBF-based system. The "trick" was to store all data in a single table with a few trivially indexed subtables and packed-table-blobs for tabular data. Shocking, I know. It's not "whatever you do", it's a matter of being RDBMS practicioner vs SQL pedant, which is where all the real complexity comes from. If data cannot be collected in a reasonable time for a primary form, it's bad design by definition. It's more reasonable to spend a few minutes to collect a report required once a year than spend a minute on a form required often.
Again, not criticizing you for this mess, but it's not something a generic ui framework should solve for.
Plus the article only refers to React, but it could have stayed a bit more abstract about the techniques.
Hey, at least when DHH jumps on the third rail of the hypermedia bandwagon I can laugh about the 500ms delay of a dropdown to show a calendar in his mail app, and I respect him for that.
I liked the following line better: "The main reason a page may contain so many requests is to improve performance and user experience, specifically to make the application feel faster to the end users."
I understand why you'd use Tanstack Query or similar solutions most of the time. I wish the mental overhead of using them was smaller.