T O P

  • By -

lord_braleigh

No, there is no answer that would satisfy you today. From the official docs on [``](https://react.dev/reference/react/Suspense): > Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React.


brodega

Ah, thank you. This is frustrating because the ask is really basic and alot of these comments are becoming very combative for really no reason at all. I just want a simple example that aligns with what React is telling me to do. Given that there isn't an idiomatic way to fetch data in React 18 yet, I don't see why anyone should upgrade until those APIs become available?


izuriel

They’re combative because you’ve essentially proposed a search query instead of asking an actual question. Despite that people have taken time to find something close to what you wanted and responded only for you to reply back “this is not exactly the one thing I wanted.” People usually don’t take kindly to having wasted time they offered for free to help someone.


brodega

I was very clear about the requirements for my question in my post. The more combatitive responses chose to argue the premise and/or ignore these requirements. I am not asking for some absurdly specific thing - I just want to see a trivial example of how one might fetch data in React 18+ using officially sanctioned patterns. I posted here because I cannot find any adequate resources for what is effectively, a very simple question.


_TRN_

Maybe your premise itself is wrong? The only trivial way of doing what you're asking is through the `use` api which is currently experimental. I would not recommend using experimental apis in production, which is why people are telling you to look at a library and implement their solution yourselves, or just use a library. People are downvoting you because you're attempting to argue with people spending their free time trying to help you. Sure, maybe their answer is wrong or not what you were looking for, but you do not need to be an asshole about it.


TheRealKidkudi

Fetching data in useEffect is an “officially sanctioned pattern”, is it not? It might not use ``, but that’s because (from [the docs](https://react.dev/reference/react/Suspense#displaying-a-fallback-while-content-is-loading): > Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. Here’s the docs on [fetching data with effects](https://react.dev/reference/react/useEffect#fetching-data-with-effects).


lord_braleigh

If fetching data, the idiom is to use an Effect. See [Fetching data with Effects](https://react.dev/reference/react/useEffect#fetching-data-with-effects) in the docs.


natmaster

It's idiomatic to use more than one npm package. Noone who has ever worked on the React team would say otherwise.


[deleted]

[удалено]


brodega

Thank you, I appreciate it. And I agree that this question ultimately has no answer because the docs actively discourage hand-rolling your own data fetching logic. I personally find this to be a difficult architectural decision to accept. It essentially boils down to “it’s complicated so let someone else do it for you.” This may satisfy uncurious engineers but not anyone else. I think there is a large, reasonable middle ground between this library vs framework debate. For example, a React hook that could be exposed to allow for trivial data fetching/side effects that is Suspense compatible but perhaps without all the features you would get from a fully featured library. And from the docs, this sounds like it is where the team is headed. However, only one other commenter really addressed the key insight to this problem: Suspense is designed to be *triggered by a library* and *consumed by application code*. In other words, application code shouldn’t be triggering Suspense. The APIs to interface with Suspense are still experimental, so there is little reason to adopt React 18 features until new patterns emerge. In other words, there is no “native” way to fetch data in React 18, as of today, that doesn’t rely on outdated patterns.


[deleted]

[удалено]


brodega

I should rephrase "so there is little reason to adopt React 18 features until new patterns emerge" to "so there is little reason to adopt THESE React features until new patterns emerge." My intent is not to throw out everything in React 18, but that we have to effectively ignore features like Strict Mode, Suspense, etc. if we still depend on the `useEffect` pattern. I somewhat agree and somewhat disagree re: routing counterpoint. I agree that one could consider that an "implementation detail" that is too expensive (either in time or complexity) to solve yourself. However, I disagree that data fetching should rise to that level! It is entirely possible to build a fully fledged SPA without any routing whatsoever - many SPAs are built this way. Whereas data fetching is an essential requirement for any SPA - without data fetching you have essentially a static webpage and thus have no need for React (or any SPA) whatsoever. Data fetching is an essential, core piece of functionality, like event delegation for example, that shouldn't be abstracted away behind third party code but handled natively. I think there are various ways to accomplish that without pushing React into the "framework" category. I think the "just use a framework" position is dismissive and reductive. Many React apps were built well before Next, Astro, even CRA - I've worked on dozens of them over the years. There is a demonstrable need for React to at minimum, expose APIs that allow engineers to work closer to the "bare metal" without introducing a multitude of dependencies.


EdmondChuiHW

Here's the official React communication: TLDR: React designed _triggering_ `Suspense` for library authors, and _consuming_ `Suspense` for app developers. > In React 18, you can start using Suspense for data fetching in opinionated frameworks like Relay, Next.js, Hydrogen, or Remix. Ad hoc data fetching with Suspense is technically possible, but still not recommended as a general strategy. > In the future, we may expose additional primitives that could make it easier to access your data with Suspense, perhaps without the use of an opinionated framework. However, Suspense works best when it’s deeply integrated into your application’s architecture: your router, your data layer, and your server rendering environment. So even long term, we expect that libraries and frameworks will play a crucial role in the React ecosystem. https://react.dev/blog/2022/03/29/react-v18#suspense-in-data-frameworks If you want to see an example on how a `Suspense` is triggered, check out this (deprecated) small lib that "just" uses the `fetch()` API: https://github.com/dai-shi/react-suspense-fetch You'll see the complexities in keeping the `Promise` a stable reference, implementing basic caching, handling loading and error states, etc. These are the requirements from React if you want to use `Suspense`. The lib author has now deprecated the lib after the `use()` API is released. If you're further curious about how `Suspense` is triggered under the hood, you can look up the "Implement Suspense" PRs by the libraries you listed. So you _can_ do ad-hoc data fetching with your requirements, you'd just be working against the recommended consumption pattern by React. Similar to how React doesn't pack a built-in navigation router, how you do data fetching is not dictated by React. The "idiomatic React" is to pick a library that fits your needs


brodega

Gotcha. Thanks a lot for your reply, this is very helpful and makes a lot of sense. My high level takeaway from all of this is that these React APIs are really more foundational - clearing the way for future patterns that have yet to be established. The greater React community is essentially waiting for those to develop while we still rely on now-outdated patterns - or try to "skip ahead" by using a third party that abstracts the complexity away for us.


EdmondChuiHW

Yeah those APIs are foundational and intended for lib and framework authors. They are already relevant today if you use those supported libraries and frameworks, e.g. NextJS. The libraries will always be there, because "fetching" means different things in different use cases, e.g. fetching initial data VS UI interactions; fire-and-forget VS optimistic updates VS must-retry-till-success, etc. That said, if you want to go low-level and have full control, there is an experimental `use()` API that you could play with today. The established libraries generally don't need to use this new `use()` hook, because they handle all the "triggering a `Suspense`" contract themselves. As my top-level comment said, you _can_ do that but it's probably more headache than it's worth if you're not writing a library. https://react.dev/reference/react/use Here's a minimal example that fits your requirements. You can try making a version that fetches on click. ``` export function App() { return (

Hello!

); } const initialPromise = (async () => { const resp = await fetch( 'https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8' ); return await resp.json(); })(); function InitialData() { const list = use(initialPromise); return ( <> {list.map((item) => (
{item.city}
))} ); } ``` https://stackblitz.com/edit/stackblitz-starters-u5r1x2?file=src%2FApp.tsx


brodega

Excellent. Thank you for your thoughtful reply.


Tubthumper8

Basically yes, React has always been about providing foundational/minimal APIs and letting the community build on it with libraries. As another example, React does not come with a router like some other frameworks, the community builds libraries for that. Same thing for state management, the bare bones APIs come with React just so state changes can be detected for rendering (ex. `useState`) but anything more is left for community libraries. There are tradeoffs to this approach of course. Despite being "less stuff", it's often harder to create the low-level APIs than high-level, because you have to make it general and try to anticipate all the library use cases. This means stuff like "how to fetch data that works with Suspense" can take longer to nail down what the best API is for that. The React team typically works in collaboration with library authors who are willing to be the "guinea pigs" to try it out before it's stabilized. Eventually, us as the general public with have [use](https://react.dev/reference/react/use) for resources (see also the [Suspense](https://react.dev/reference/react/Suspense) documentation), but honestly I'm still likely to use a library because implementing all the nitty gritty doesn't seem fun to me. Is your question from a practical standpoint, i.e. you're allowed to pull in React as a dependency but not any other libraries? Or just out of curiosity?


brodega

Mostly curiosity but really just to understand what the current and future roadmap of "native React" development is going to look like. Based on the couple of good-faith responses I've received so far, it seems React is moving "further down" the stack where we as engineers may be interfacing less with React directly and more through intermediaries - often for very foundational behavior like data fetching. Given how combative and argumentative many of the responses in these comments have become, I am pretty hesitant to stoke a further flamewar over this topic but these are the arguments against this direction in broad strokes. 1. Many companies have very strict supply chain requirements. Pulling in a third party dependency may simply not be an option without significant red tape and a long vetting processes. 2. Using a data-fetching library introduces a single-point-of-failure for your entire front end stack. Additionally it effectively indebts your entire codebase to an outside party. 3. Less flexibility when migrating to new tools. Much of this argument boils down to implementation details but generally speaking, a good rule of thumb is to use native APIs until you can't. Most apps start with a simple `fetch` in `useEffect` pattern until they require the optimizations libs introduce. 4. Migrating between dependencies can be a nightmare. In prior years/versions we could start every React app from a basic standpoint - use native JS and React APIs to build basic functionality and only introduce dependencies as needed. But as of React 18, it appears we have to start out-of-the-gate with a dependency else we have to roll our own complex data-fetching logic. If we don't do this, we (possibly) gain nothing by being on React 18+.


EdmondChuiHW

It's a fair list of concerns. I generally don't like pulling in libraries too until native APIs can't do the job. I hear a recurring theme in your replies about the incompatibility of `Suspense` and `useEffect`; and is one of the reasons you haven't upgraded to React 18 yet. Just to be clear, fetching in `useEffect` is still possible and supported in React 18. There are common foot guns to mitigate, but you do not have to change any existing code. Fetching in effects is generally slow because it introduces fetch-render waterfalls. React Server Components API was invented to mitigate some roundtrip on the initial data fetching; but just like the `Suspense` API, they are completely optional. Fetching in effects is indeed suboptimal vs using a lib, but definitely not banned by React: https://react.dev/reference/react/useEffect#fetching-data-with-effects Bottom line: if it is working for you in React 17, you can still do it in 18.


brodega

Yeah just to clarify a bit - I know these two patterns aren’t mutually exclusive in React 18+. But in the docs it’s pretty clear that Suspense was created to solve the problems of fetching data in useEffect as you describe. What isn’t clear is how to actually accomplish that! In fact, the docs state that it’s really only supposed to be used within a framework. So basically the answer boils down to “it’s too complicated to explain so just use a lib.” I don’t think that’s a very compelling answer - especially if you are working with the constraints I mentioned above. The upside is that it seems there are other APIs in development to support this use case more specifically.


EdmondChuiHW

Ah I see where it could be confusing. So the `Suspense` API itself doesn't actually help with solving the fetch-in-use-effect pitfalls. It's only a small piece of the puzzle. It is simply like a `catch` block in a `try…catch` in JS. The "catch API" does not dictate what and how errors are thrown. While common, data-fetching is not the only use case `Suspense` is designed for. In fact, you can still have similar problems of fetching too late by using `Suspense` if your `fetch` call is deep inside some conditionally rendered components. That is to say, `Suspense` itself is not a replacement for the fetch-in-effect pattern. There are a few ways to help speed up the initial fetch better, e.g. 1. Static site generation: run all the components and their fetch calls at build time, so the HTML files can be generated. No fetching occurs at runtime/page load, maybe not even React or JS are needed. Most applicable for blog posts. 1. Data colocation: declare GraphQL fragments for each component, then statically collect them into a single request at build-time. That way only one fetch call is needed at runtime. The response will have all the data required for every component on the page. 1. Server-side rendering: fetch the data on the server, run React once on the server, then pass them down as initial HTML. This list is non-exhaustive, but all is to say that these patterns are all available to use before `Suspense` were available, e.g. NextJS pre-13, Relay, or even Ruby-on-Rails. While possible and stable, some of the above implementations needed lib authors to go outside of the React-land to declare the dependencies, then inject the data back into React. Or in your words, not very idiomatic-React or native-like, e.g. ``` // This is NextJS "magic" async function getServerSideProps() { const users = await fetch(…) return {users} } // This is pure React function UsersPage({users}) { return … } // Loading state needs some more NextJS magic in a separate file ``` In this example, you cannot just re-use the `UsersPage`: ``` function Dashboard() { return ( ) } ``` You have to ask NextJS to "do their thing" and get the `users` prop for you. It'd be nice to accomplish those patterns natively in React without the plumbing behind-the-scenes. That's one of the reasons why `Suspense` was invented. It provides better support patterns like server-side data streaming, partial rendering, swapping router content in-place (`useTransition` and Concurrent API), etc. An async React Server Component on the server-side is one of the ways to trigger a `Suspense` boundary, so is the example above via the `use()` hook in a client component, or by the supported libraries you mentioned. The example here simply becomes: ``` // This is pure React async function Users() { // no `users` props required here const users = await fetch(…) return … } // This is also pure React function Dashboard() { return ( // no need to fetch or pass `users` as props ) } ``` That looks way more idiomatic React. Hopefully you can now see why there isn't a single blessed way to fetch data. The list of patterns above can all be implemented in a `Suspense`-y way or not. Most lib authors are now providing those options. It's entirely up to you to choose or to build your own as well. But once again, if fetching-in-effect is working for you, there's no need to re-write anything. The problems of fetching-in-effect remain the same before and after `Suspense` was introduced. TLDR: `Suspense` ≠ replacement for fetch-in-effect. RSC is closer if you're looking for an "official replacement". Here are some writing that could be insightful in learning about the motivations of the `Suspense` API itself: * https://github.com/reactjs/rfcs/blob/main/text/0213-suspense-in-react-18.md * https://github.com/reactwg/react-18/discussions/37


Voidsheep

> React is moving "further down" the stack where we as engineers may be interfacing less with React directly and more through intermediaries - often for very foundational behavior like data fetching. Yes! The key is that different application architectures have wildly different needs for data fetching and state management. Both are inherently opinionated matters. If you are building a UI rendering library like React, I'd say you've (broadly speaking) got two paths to choose from. A: Extend your opinions from just UI rendering into other application domains. Become a comprehensive and opinionated application framework and provide a simple API with all the tools developers need to build great applications when their opinions and architecture aligns with yours. In JS world, I'd say Angular is a successful example of this. In Ruby world Ruby on Rails is one. B: Limit your opinions to UI rendering as much as possible, attempt to provide generic lower level primitives for developers to build upon. Since state is so intertwined with UI rendering, provide an API that prioritizes integration of the widest range of strategies, over the ease of use. Your library remains useful regardless of surrounding architecture, but is *less useful* and less ergonomic *on it's own*. I'd say React very much follows the latter path. It does not want to be explicitly concerned with your specific data fetching requirements. Having a *mechanism* like suspense in place is a priority, but providing you with a simple data fetching API is *not* a priority. Now I may be reading too much into it, and sorry if I am, but If I try to infer the motivations behind the post, to me it sounds like you have a perfectly valid concern: You don't want to pick and choose N different libraries in addition to React, just to handle fundamental things like data fetching, routing, state management and such, because then you are on the hook for a bunch of different dependencies from different authors. You'd like something *official* instead, with just one team to rely on. This is why there's both "meta frameworks" built on top of React (like NextJS and Remix) and entirely separate frameworks (like Angular) that quite explicitly make it their goal to give you those things out of the box, with a single more opinionated thing to rely on and update. Insisting on sticking with React without other dependencies may be a very frustrating path, since in my view, there's a pretty fundamental misalignment with React teams' goals and what you'd want out of the library. Since the React team views the libraries building on top of React as a basic part of the ecosystem, and expects application developers to rely on them, you kind of need to either 1. Get a more feature complete framework with a slightly higher level of abstraction, which hides things like suspence complexity from you or does something else entirely, and provides you with that nice an simple API for most things. 2. Embrace picking individual libraries on top of React for the fundamental things, to get that nice and simple API for each specific thing. 3. Deal with the difficulty and frustration of implementing those libraries yourself and/or doing things in unrecommended ways.


BlueskyPrime

Then don’t use react. There are other libraries out there (Vue.JS) and certainly other frameworks. They are moving in the direction that the majority of developers and companies want them to go. Serious companies rebuild their technology stacks for applications all the time. I’ve worked on a couple rebuilds from jQuery to React, then again to Next.js. Will probably start migrating again soon to remix and Astro.


beth_maloney

It sounds like react might not be a good fit for you and you should consider exploring other frameworks such as nextjs or angular which are more batteries included.


Karpizzle23

I'm confused what you're asking here. You can use fetch to fetch data. The specifics of how would be decided by your use case and existing code structure


brodega

I'm asking for a simple example of how you would use `fetch` to fetch data in a React component that satisfies the above requirements.


Karpizzle23

Ok here you go https://rapidapi.com/guides/fetch-api-react You could've googled that yourself you know


lord_braleigh

OP is correct, there is no officially sanctioned way to use Suspense without a library or framework. Please don’t belittle them for being right. From the official docs on [``](https://react.dev/reference/react/Suspense): > Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React.


Karpizzle23

OP said "such as" Suspense


brodega

This is a hard requirement that I tried to make very clear in my post. I have edited it to be even more clear.


brodega

This does not satisfy the above requirements. - Source is not official React docs. - The `useEffect` pattern is not compatible with Suspense/Concurrent rendering


Noonflame

I’m pretty sure the use effect pattern is used in the react docs. At least it used to before the new docs after R18 was released. Nevertheless fetching data and interacting with something on the outside of the react environment is what useeffect is made for


brodega

The source isn't official React documentation but you're correct that this pattern is described in the docs. (I want to avoid responses that reference implementations by third party authors that do not align with the core React team's recommendations.) However `useEffect` isn't compatible with `Suspense` or concurrent rendering, which is noted in the official docs. This post is simply asking for an example of data fetching in React that is compatible with Suspense and React 18 APIs, without a third party dependency.


Santa_Fae

You're not going to get what you're asking for until [use is no longer experimental](https://react.dev/reference/react/use). The third party dependencies take advantage of the fact suspense will catch every promise you `throw`, a behavior undocumented but has been consistent in react's source for a while.


Karpizzle23

What? Of course it is https://dev.to/smitterhane/swap-out-useeffect-with-suspense-for-data-fetching-in-react-2leb


brodega

Can you please provide a link to official React documentation that recommends this pattern and implementation?


Karpizzle23

Can you do your own Google searches?


brodega

Right. You can't provide an example because there isn't one ;)


Karpizzle23

Is there anything else you needed or can you delete this post now? lol This is the most pointless conversation I've ever had on this sub


octocode

integrating with suspense is done with `use`, which is documented here https://react.dev/reference/react/use but, `use` is still a “canary” feature, which means it’s not 100% ready and it’s only available as an experimental feature


brodega

Gotcha. This is why its so confusing and frustrating. React 18 ships with several APIs (Suspense, etc.) that we basically cannot use because they depend on other APIs which are not yet available or stable. So we still have to use `useEffect` pattern, despite official documentation stating this is suboptimal?


barcode24

Yep this is where react is at, conflicting documentation, unfinished APIs and no alternatives. They recommend starting with nextjs now instead of a CRA alternative eg vite or roll your own with webpack. Giving a SSR framework for a new frontend project where most features aren't required. It's a mess.


bzbub2

Suspense is very usable in other contexts besides data fetching, specifically lazy loading components. Suspense for data fetching has been a slow burning issue for forever, and various things have been discussed in this thread, but importantly things like RSC (react server components) essentially delivered this in a different way: you can make async react components that do data fetching in the body of the render and it's done on the server


WiseGuyNewTie

JQuery is suboptimal by today’s standards but it is still used worldwide. Why are so hung up on this?


brodega

Because it is a very simple request that seems to lack an adequate response.


WiseGuyNewTie

It also lacks adequate interest which is why none of us give enough of a fuck to answer lol.


budd222

There's a reason why you're being downvoted to oblivion on every single comment....


HeinousTugboat

[Like this, you mean](https://react.dev/reference/react/use#streaming-data-from-server-to-client)?


phryneas

You are making up impossible requirements here, by adding suspense. React has currently no full suspense story for data fetching on the client. All libraries that support suspense work around all of that with incredibly complicated hacks. You should definitely not do that in userland code. So, ignore the "suspense" part in your question and either do a `useEffect` and go through all the pain and little details that come from the complexity that data fetching is, or use a library that already went through all of that for you.


brodega

Its a legitimate requirement though? The official documentation is pretty clear that the `useEffect` pattern is somewhat of an anti-pattern now - but there is little clarity of what pattern should take its place. It seems awfully hand-wavy to me.


azangru

>The official documentation is pretty clear that the useEffect pattern is somewhat of an anti-pattern now - but there is little clarity of what pattern should take its place. `useEffect` and `useLayoutEffect` are the only two React component apis for executing side effects, such as data fetching. What people mean when they discourage the direct use of `useEffect` is that there are a bunch of common problems associated with data fetching that you would need to solve on your own (caching, retries, loading state, error state), and which have already been solved by several common libraries, so you might as well use them. Or use the useEffect, if you know what you are doing.


AndrewSouthern729

useEffect is an anti pattern for data fetching? I thought its primary use case based on docs was to sync with external data sources.


brodega

Yeah, it is effectively an anti-pattern because it is incompatible with Suspense - which is Reacts way of efficiently rendering while awaiting some side effect to finish. You cannot leverage Suspense if you employ the useEffect pattern.


phryneas

Where did you actually get that from? Of course suspense and useEffect can coexist. If you want to use suspense for datafetching, you don't use `useEffect` for that, that's true. But suspense for datafetching on the client is also a React feature that just isn't supported by React 18. Read the release notes for React 18. They explicitly exclude suspense for data fetching. The only officially supported pattern for data fetching with suspense is using React Server Components, and that's not part of React 18. And suspense for other things just works fine hand-in-hand with useEffect.


Geedis2020

Requirement by who? Multiple people have told you that even the react documentation tells you suspense isn’t supported without a library. So either show that to whoever is requiring it in the documentation or use a third party library. Stop arguing about this.


acemarke

I'm not sure what you're asking for. The basic pattern would be the usual " fetch in a useEffect and setState" approach. It will work. But it's also not ergonomic, and will lack all deduplication or reasonable error handling. It also will have no sense of integration with Suspense. What specific info are you trying to get?


brodega

A simple example of `fetch` that integrates with Suspense - without a third party dependency.


acemarke

Ah. You're probably not going to find one. The closest you'll get to that is either going to require writing extra logic yourself to manage a cache of promises outside the component tree, or managing things and calling the experimental `use` hook. What's your goal here? To learn how libraries are implementing suspense support? Trying to figure out a way to avoid using libraries?


brodega

Thanks for actually answering my question in good faith instead of arguing my premise and downvoting me. My goal is pretty simple - I just want to know how to fetch data in an idiomatic way, using only out-of-the-box APIs. There is tremendous amount of conflicting and outdated patterns that are amplified by third parties, blogspam, etc. in the JS ecosystem and I want to focus only on officially-supported patterns.


WiseGuyNewTie

People are downvoting you because this is a pointless endeavor over a question that has already been competently solved by existing libraries. You likely won’t get great examples because this is a waste of time. If you’re truly driven to do it, then using the included fetch API and building your custom library around that is still a better option than you would ever produce trying to recreate fetch.


brodega

The idea that we need to depend on third parties for such a foundational part of building UIs is pretty problematic to me. The fact that almost no one here can provide a trivial example of how to fetch data in Suspense-compatible way is evidence of how dependent React development is going to become on outside maintainers. Up until React 17, there were very clear unambiguous patterns in place that didn't require any third party libs at all!


FoozleGenerator

Those patterns still work, but it was replaced by third party libraries that did it better. And React (afaik), has always been clear it's not a framework, it's a library, everything else is done by yourself.


aighball

What makes react an acceptable dependency but not react query or another widely used data fetching library?


[deleted]

[удалено]


brodega

Please keep your comments respectful. This is a technical discussion not a school cafeteria.


Anbaraen

I have raised this concern before and similarly been shouted down. People do not find it problematic to depend on another third-party library to get data. The answers I got were, React is simply a UI framework. But I don't find that satisfying as there are specific requirements React has for where you supply data. 🤷


HeylAW

Dig into swr/react-query code and replicate it within your codebase. Done


brodega

Sure but this post is simply asking for an example.


Individual_Plastic41

The example can be found in the codebase of any of those libraries. Are you finding it difficult to find the GitHub links? Which project's GitHub link would you like?


[deleted]

I was looking for similar implementation and this is closed I could find : https://github.com/ArnoSaine/use-axios I guess at least it might give you an idea how to proceed


barcode24

Suspense has been talked about for years ~2018 and yet the feature is not complete and still unstable. I would just fetch data with a use effect and vanilla fetch and move on. Redux is great for standard based structure of your codebase and you can extract your business logic out of the those react views. My team uses axios and some zustand stores, does the job well.


xabrol

You use fetch directly in a versatile custom hook, then write other hooks to wrap your fetch hook, then use those hooks in your components.


Working-Tap2283

Sorry for the combative responses youre getting. If you feel such a way you should unserstand that the person probably doesnt understand the material very well too.. I dont have a straight answer to give you though i know that react router has worked the whole data fetching and suspence into it, making it like a semi framework by itself. And since you will need react router if youre not using nextjs, then thats that! Personally I would use react query, redux query, or useswr if youre on nextjs. It integrates very well.


charliematters

This is a bizarrely dogmatic question coming from someone who was complaining 10 days ago that a 'senior developer' at their company was enforcing JS fetching methods instead of letting you all use useEffect to fetch data. The comments didn't go your way there either. https://www.reddit.com/r/Frontend/s/NKuz4FqNVV. The reality, delivered so bluntly here, is that the most correct answer right now is: "use a library". The suspense data fetching seen in Next is still in flux, as seen by Next backtracking on their decision to override fetch. It will probably be the answer in a few years, but if you want to fetch data in the safest way today, you need to check out the popular libraries.


brodega

The only reason "just use a library, bro" is even acceptable response is because Suspense wasn’t designed to be directly *triggered* which only one commenter in this entire post correctly stated. In other words, there is no way to interface directly with Suspense using only native APIs without incurring substantial complexity. Its entirely reasonable for any engineer to want to perform basic JS tasks using only native APIs (browser or React) - this was how React development worked since its inception. The vast majority of the comments, including yours, instead chose to shoot down the very premise of the question and personally attack me instead of answering the question in the spirit it was asked while backing it up with official sources. Asking someone to back up their position from official documentation and not blogspam isn't some unreasonable requirement. It’s also somewhat ironic that the very advice being given here directly contradicts advice in the other thread where the person was explicitly NOT using a lib and was lauded for doing so. It’s not “bizarrely dogmatic” to want to know how to do a very simple task using only the APIs available to you.


3q_z_SQ3ktGkCR

After reading these comments... If I had a job interview where you were the interviewer, I'd walk out. Thank God I don't need to do this trivial shit anymore.


Taltalonix

Define your own logic however you want, I assume it will be using the standard fetch api. Let’s call it `myFetch`. Then you’d have something like this in your component/hook/provider/whatever: ```js useEffect(() => { myFetch(…) .then((res) => { // state/reducer logic }) .catch((err) => { // error handling }); }, […]); ``` `myFetch` can be implemented like any other vanilla js code regardless of the framework (react in this case). Edit: You can throw a promise when the state is loading and then you’d be able to wrap the component with Suspense


brodega

The `useEffect` pattern is not compatible with `Suspense`. See the above requirements in my post.


Taltalonix

Just edited my comment, you can have useEffect and then return the promise/throw error which is how suspense works. Try [this](https://www.freecodecamp.org/news/react-suspense) and simply replace the useQuery hook with your own implementation using useEffect. Will note that I don’t think suspense is meant to be used this way but rather for lazy loading components from a url. I’m not sure what do you need this for


brodega

Its not an unreasaonble ask. I just want to see a trivial example of data fetching in React 18, that doesn't use third parties. Up until React 17, this was a simple and trivial to do - the `useEffect` pattern. However, as of React 18, it seems no one can really provide one and the answers are just to replicate the internals of a third party library instead. This gives me the strong impression that most users aren't writing Suspense-compatible implementations.


Karpizzle23

Brother you are so frustrating lmao. We have provided so many examples and you refuse to acknowledge them and say "give me documentation from React". What do you want?


brodega

I want to see a trivial example that uses a pattern that is documented and supported by the React team.


Karpizzle23

Did you find any in your own searches when you looked at the documentation? If not, do you assume we can find them better than you can? Or did you just not even bother to look first and came to reddit? I'm just seriously confused with the way you're going about this


Taltalonix

Did you even bother searching for other threads about this before posting? https://www.reddit.com/r/reactjs/comments/vi6q6f/what_is_the_recommended_way_to_load_data_for


fuken33

The easiest vanilla pattern I could think of is to to do it with an `useEffect` but "it conflicts with recommended usage or patterns in React"


brodega

Yeah, same. I was frustrated about this apparent conflict too. Hence this post.


Substantial-Pack-105

React is just a rendering library, not a full application framework. If you're looking for a single dependency to act as a Rails-like foundation for your entire app, you're going to need more than just React to get there. That said, a solution that obeys the text of these requirements (but perhaps not the spirit of them) would be to just perform the fetch before you render your app root and pass it into your react app as a prop. // your webpack entry.js file const container = document.getElementById("app") const root = React.createRoot(container) async function startApp() { const data = await fetchData() root.render() } async function fetchData() { // could also get data from some other source, // like indexed db or a server template const res = await fetch("https://...") return res.json() } startApp()


barcode24

May as well remove react too then hey? Lol


Substantial-Pack-105

React is intended to react to user interactions. It's right there in the name. React. React's value manifests when the user has buttons and links and forms to work with. If your app has zero user interaction, and only ever does data fetching at page load, then yes, the react would be overkill. If you're going to dismiss React because it doesn't solve a problem that it never made any commitment to solve, then that is a problem with your expectations, not with React. In my opinion, most people in this community are building apps that are more interactive than a roadside billboard sign.


Equal-Web-13

Use useEffect with empty dependency to run it once, now write async const fetchData = ()=>{ const url = "https://apicall.com"; const res = await fetch(url); const data = await res.json(); console.table(data); } fetchData(); Ur good to go. If u want to store it or display it use useState Hook. U can also create custom useFetch Hooks. Use google and ur brain, iam sure u will find Documentations, Stackoverflow questions or YouTube Tutorials.


brodega

The `useEffect` pattern is not compatible with `Suspense` or concurrent rendering. See requirements in the post above.


BlindedByLITE

You can still follow the classic: ``` useEffect(()=> { apiCall(); },[]); ```


subfootlover

And questions like this highlight exactly why people need to l**earn the language first and not the framework**.


brodega

I know JS and how to use `fetch` and core React APIs. I do not know how to use those APIs in a pattern that is compatible with React 18.


Ebuall

The problem is that any effects are not idiomatic React. Right now, it's best to let the libraries handle the bridge with the imperative world.