React query graphql

React query graphql DEFAULT

Queries: Loading Links

Preparing the React components

The first piece of functionality we’ll implement in the app is loading and displaying a list of elements. We’ll walk up our way in the React component hierarchy and start with the component that will render a single link.

This is a simple React component that expects a in its and renders the link’s and . Easy as pie! 🍰

Next, let’s implement the component that renders a list of links.

Here, we’re using local mock data for now to make sure the component setup works. We’ll soon replace this with some actual data loaded from the server - patience, young Padawan!

Run the app to check if everything works so far! The app should now display the two links from the array:

Run the app to check that it's working

Writing the GraphQL query

Let’s now load the actual links that are stored in the database. The first thing we need to do for that is define the GraphQL query we want to send to the API.

Here is what it looks like:

We could now simply execute this query in a Playground (against the application schema) and retrieve the results from the GraphQL server. But how can we use it inside our JavaScript code?

Queries with Apollo Client

The most common (and probably the most flexible) way of making queries with Apollo Client is to use the hook it provides. With the hook, all we need to do is pass a GraphQL query document in and Apollo will take care of the fetching and will surface the returned data and any errors for us.

Open up and add the query to the top of the file:

Let’s take a moment to walk through what’s happening with this new code.

The variable uses , a library that uses tagged template literals to parse the GraphQL query document we define. This query document is then passed into the hook in the component.

This hook returns three items that are relevant for our purposes at this point:

  1. : Is as long as the request is still ongoing and the response hasn’t been received.
  2. : In case the request fails, this field will contain information about what exactly went wrong.
  3. : This is the actual data that was received from the server. It has the property which represents a list of elements.

The injected props actually contain even more functionality. You can read more in the API overview.

When the component initially renders, there won’t be any information on the variable. For this reason, we need to check that is truthy before trying to render any of the links that will come out of it. Once our GraphQL request resolves with some data, the component will re-render and will be truthy. Our links are available on which we can map over to render.

That’s it! You should see the exact same screen as before.

Note: If the browser on only says error and is empty otherwise, you probably forgot to have your server running. Note that for the app to work the server needs to run as well - so you have two running processes in your terminal: One for the server and one for the React app. To start the server, navigate into the directory and run .

Sours: https://www.howtographql.com/react-apollo/2-queries-loading-links/

Let's go through the five best ways that you can fetch data with React from a GraphQL API.

While there are a couple of popular libraries which are made to interact with GraphQL APIs from a React application, there are many different ways to fetch data with GraphQL.

I've included code samples that show you how to fetch or "query" data in the shortest code possible and how to get up and running with each of these different methods of connecting React with GraphQL.

Want to build amazing apps with React and GraphQL from front to back? Check out the React Bootcamp.

Getting Started

In these examples, we'll be using the SpaceX GraphQL API to fetch and display the past 10 missions that SpaceX has made.

Feel free to use the code below if you are attempting to connect your React app with a GraphQL API. In these examples, we're going to go from the most advanced GraphQL client library for React to the simplest approach to querying a GraphQL endpoint.

1. Apollo Client

The most popular and comprehensive GraphQL library is Apollo Client.

Not only can you use it to fetch remote data with GraphQL, which we're doing here, but it allows us to manage data locally, both through an internal cache as well as an entire state management API.

To get started with Apollo Client, you need to install both the main Apollo Client dependency, as well as GraphQL:

The idea behind the Apollo Client is that it will be used across your entire application. To do this, you'll use a special Apollo Provider component to pass a created Apollo client down your entire component tree.

When you create your Apollo Client, you need to specify a value, namely a GraphQL endpoint. Additionally, you need to specify a cache.

Apollo Client comes with its own in memory cache, which is used to cache or locally store and manage your queries and their related data:

Once you've set up the Provider and client within your App component, you can use all of the different React hooks that Apollo Client gives you for all the different GraphQL operations. These include queries, mutations, and subscriptions. You can even use the created Apollo Client directly using a custom hook called .

Since you're just querying data here, you will use the hook.

You will include a GraphQL query as its first argument to write your query. You'll use the function , which does a number of things, such as giving you editor syntax highlighting and the auto formatting functionality if you use the tool Prettier for your project.

Once you execute this query, you get back the values , , and :

Before you display your data, your missions, you want to handle the loading state. When you are in a loading state, you are fetching the query from a remote endpoint.

You also want to handle any errors that occur. You can simulate an error by making a syntax error in your query, such as querying for a field that doesn't exist. To handle that error, you can conveniently return and display a message from .

2. Urql

Another fully-featured library that connects React apps with GraphQL APIs is urql.

It attempts to give you many of the features and syntax Apollo has while being a little bit smaller in size and requiring less setup code. It gives you caching capabilities if you choose, but it does not include an integrated state management library like Apollo does.

To use urql as your GraphQL client library, you'll need to install the packages urql and GraphQL.

Just like Apollo, you'll want to use the dedicated Provider component, and create a client with your GraphQL endpoint. Note that you do not need to specify a cache out of the box.

Very similar to Apollo, urql gives you custom hooks that handle all the standard GraphQL operations, and therefore have similar names.

Again, you can use the hook from the urql package. Although instead of needing the function , you can drop it and just use a template literal to write your query.

When calling , you get back an array which you can destructure as an array instead of as an object. The first element in this array is an object, called , which gives you a number of properties that you can destructure: , , and .

In an identical fashion to displaying the data that you fetch with Apollo, you can handle both your error and loading states while you're fetching your remote data.

3. React Query + GraphQL Request

It's important to note at this point that you don't need a sophisticated, heavyweight GraphQL client library like urql or Apollo to interact with your GraphQL API, as we will see later.

Libraries like Apollo and urql were created not only to help you perform all the standard GraphQL operations, but to better manage the server state in your React client through a number of additional tools. All this along with the fact that they come with custom hooks that make managing repetitive tasks like handling loading, error, and other related states simple.

With that in mind, let's take a look at how you can use a very pared-down GraphQL library for your data fetching and combine that with a better means of managing and caching that server state that you're bringing into your application. You can fetch data very simply with the help of the package .

GraphQL Request is a library that doesn't require you to set up a client or a Provider component. It is essentially a function that just accepts an endpoint and a query. Very similar to an HTTP client, you just have to pass in those two values and you get back your data.

Now if you want to manage that state across your app, you can use a great library normally used for interacting with Rest APIs – but it's equally helpful for GraphQL APIs – and that is React Query. It gives you some very similarly named React Hooks, and , that perform identical tasks to what the Apollo and urql hooks perform.

React Query also gives you a bunch of tools for managing state, along with an integrated Dev Tools component that allows you to see what's being stored in React Query's built-in cache.

By pairing your very basic GraphQL client, GraphQL request, with React Query you get all the power of a library like urql or Apollo.

To get started with this pairing, you just need to install React Query and GraphQL Request:

You use React Query's Provider component and create a query client where you can set some default data fetching settings if you like. Then within your app component itself, or any child components of , you can use the hook.

To store the result of your operation in the React Query cache, you just need to give it a key value as the first argument to serve as an identifier. This allows you to very easily reference and pull data from the cache, as well as to refetch or invalidate a given query to fetch updated data.

Since you're fetching launch data, let's call this query "launches".

Once again, this hook will return the result of making that request. For the second argument to , you need to specify how to fetch that data and React Query will take care of resolving the promise that GraphQL request returns.

Similar to Apollo, you get back an object that you can destructure to get the values for the data, as well as whether or not you're in the loading state, and the error state.

4. React Query + Axios

You can use even simpler HTTP client libraries that have no relationship to GraphQL to fetch your data.

In this case, you can use the popular library axios. Once again you can pair it with React Query to get all the special hooks and state management.

Using an HTTP client like Axios to perform a query from a GraphQL API requires performing a POST request to your API endpoint. For the data that you send along in the request, you will provide an object with a property called , which will be set to your films query.

With axios, you're going to need to include a little bit more information about how to resolve this promise and get back your data. You need to tell React Query where the data is so it can be put on the property that returns.

In particular, you get the data back on the data property of :

5. React Query + Fetch API

The easiest way of all these different approaches to fetch data is to just use React query plus the fetch API.

Since the fetch API is included in all modern browsers, you do not need to install a third-party library – you only need to install within your application.

Once you have the React Query client provided to the entire app, you can just swap out your axios code with fetch.

What's a little bit different is that you need to specify a header that includes the content type of the data that you want back from your request. In this case, it is JSON data.

You also need to stringify the object that you're sending as your payload with a query property that is set to your films query:

One benefit of using axios over fetch is that it automatically handles errors for you. With fetch, as you can see in the code above, you need to check for a certain status code, in particular a status code above 400.

This means that your request resolves to an error. If that's the case, you need to manually throw an error, which will be caught by your hook. Otherwise, if it's a 200 or 300 range response, meaning the request was successful, simply return the JSON data and display it.

Conclusion

This article was dedicated to showing you a number of different approaches to effectively fetching data from a GraphQL API with React.  

From these options, hopefully you can evaluate which is most appropriate for you and your applications. And now you have some helpful code that will enable you to start using these tools and libraries much faster.

Enjoy this post? Join The React Bootcamp

The React Bootcamp takes everything you should know about learning React and bundles it into one comprehensive package, including videos, cheatsheets, plus special bonuses.

Gain the insider information hundreds of developers have already used to master React, find their dream jobs, and take control of their future:

The React Bootcamp
Click here to be notified when it opens



If this article was helpful, tweet it.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Sours: https://www.freecodecamp.org/news/5-ways-to-fetch-data-react-graphql/
  1. Mac lucci instagram
  2. Shea butter walmart
  3. Armslist las vegas

Simplify GraphQL requests with React Query, GraphQL Code Generator, and TypeScript

Using a GraphQL API comes with distinct advantages. With GraphQL, we can request the exact data we need without ever under- or over-fetching. We can also get multiple resources in a single request. At the same time, the requests themselves can serve as a form of documentation, making it is easy to understand what data is being used, where, and why.

But the most exciting feature of GraphQL is that the API is fully described by its schema, including all data types for each possible query or mutation.

Why does this matter?

Because, based on that schema, we can automatically create TypeScript types for the entire API on the frontend. What’s more is we can easily autogenerate fully-typed custom React hooks for a data-fetching library like React Query.

Let me show you how.

Setting up the project with GraphQL

React app

First, let’s create our React project with Create React App with the TypeScript template.

yarn create react-app graphql --template typescript

Deploying GraphQL API

Next, we need an API. FakeQL provides a great way to create a mock GraphQL API and deploy it. Because we will be using the default definition, we can set everything up simply by clicking Extend JSON and then Deploy. The tool generates a unique URL where we can access our new API.

Creating the data-fetching library

Now that we have our React app and our API, it is time to set up our data-fetching library, React Query.

Let’s install it:

yarn add react-query

Now, set up the React Query client.

import { QueryClient, QueryClientProvider } from 'react-query' import Posts from 'components/Posts' const queryClient = new QueryClient() const App = () => { return ( <QueryClientProvider client={queryClient}> <Posts /> </QueryClientProvider> ) } export default App

Building the components

Because our API provides a list of posts, we will use a component to display them. For the moment, let’s leave it empty.

// components/Posts.tsx const Posts = () => { return ( <></> ) } export default Posts

Next, we need a query to get the list of posts. Let’s define it in a file and co-locate it with our component:

# components/Posts/posts.graphql query Posts { posts { id title } }

Finally, let’s also add a mutation for deleting a post:

# components/Posts/deletePost.graphql mutation DeletePost($id: ID!) { deletePost(id: $id) }

Auto-generate typed React Query hooks with TypeScript and GraphQL Code Generator

We are now ready to auto-generate our custom and fully typed React Query hooks based on the requests we previously defined in our files. We will be using GraphQL Code Generator.

We start by installing it:

yarn add graphqlyarn add -D @graphql-codegen/cli

Next, we need to initialize the wizard and go through the steps:

yarn graphql-codegen init

First, we choose the type of app we are building:

Choosing Type

Then, we define our schema is by pasting our FakeQL url.

Pasting FakeQL URL

We define where our operations and fragments are:

Defining Operations Fragments

We choose our plugins:

Choosing Plugins

We choose where to write the output:

Choosing Where to Write Output

Let’s also generate an introspection file:

Generating Introspection File

We need to name our config file:

Naming Config File

Finally, let’s name our script :

Naming Script

So far, so good!

In order to generate custom React Query hooks, we need to install the appropriate plugin:

yarn add -D @graphql-codegen/typescript-react-query

And add a quick edit of the codegen.yml config file in order to make it work:

overwrite: true schema: 'https://fakeql.com/graphql/2aaf00462236e8280f4c3beb197aae54' documents: 'src/**/*.graphql' generates: src/generated/index.ts: plugins: - typescript - typescript-operations - typescript-react-query config: fetcher: endpoint: 'https://fakeql.com/graphql/2aaf00462236e8280f4c3beb197aae54'

Finally, we need to run our script.

yarn graphql:codegen

We are now done! Our fully-typed custom React Query hooks have been automatically generated and added directly to our project’s folder.

Let’s see them in action!

Making API requests

In our component, we are now ready to display the list of posts:

import { usePostsQuery } from 'generated' const Posts = () => { const { data } = usePostsQuery() return ( <> {isLoading && <p>Loading ...</p>} {data && data.posts?.map(post => ( <div key={post?.id}> <p>{post?.title}</p> <hr /> </div> ))} </> ) } export default Posts

Let’s also add the mutation we defined earlier.

import { useQueryClient } from 'react-query' import { usePostsQuery, useDeletePostMutation } from 'generated' const Posts = () => { const queryClient = useQueryClient() const { data, isLoading } = usePostsQuery() const { mutate } = useDeletePostMutation({ onSuccess: () => queryClient.invalidateQueries('Posts'), }) return ( <> {isLoading && <p>Loading ...</p>} {data && data.posts?.map(post => ( <div key={post?.id}> <p>{post?.title}</p> <button onClick={() => post && mutate({ id: post.id })}> Delete </button> <hr /> </div> ))} </> ) } export default Posts

That’s it, we now have a working example!

Conclusion

The approach described above allows us to take full advantage of GraphQL on the frontend by automating both the creation of TypeScript types for the API and the generation of custom React Query hooks for each request.

By using it, we have also substantially reduced the amount of data-fetching boilerplate code we need to write. With this tooling in place, all we need to do in order to create additional React Query custom hooks for a request is to create a file and run the script. Pretty cool, right?

Curious to play with the code yourself? Find a full working example in my GitHub repo.

Happy coding! ✨

Full visibility into production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket. LogRocket Dashboard Free Trial Banner

LogRocket is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — start monitoring for free.

Writing a lot of TypeScript? Watch the recording of our recent TypeScript meetup to learn about writing more readable code.

TypeScript brings type safety to JavaScript. There can be a tension between type safety and readable code. Watch the recording for a deep dive on some new features of TypeScript 4.4.

Sours: https://blog.logrocket.com/making-graphql-requests-easy-with-react-typescript-and-react-query/

This article shows how to fetch GraphQL data in React with the hook and attach the result to your UI. You'll also learn how Apollo Client simplifies data management code by tracking error and loading states for you.

Prerequisites

This article assumes you're familiar with building basic GraphQL queries. If you need a refresher, we recommend this guide. You can also build example queries against Apollo's full-stack tutorial server.

This article also assumes that you've already set up Apollo Client and have wrapped your React app in an component. For more information, see the getting started guide.

To follow along with the examples below, open up our starter project and sample GraphQL server on CodeSandbox. You can view the completed version of the app here.

Executing a query

The React hook is the primary API for executing queries in an Apollo application. To run a query within a React component, call and pass it a GraphQL query string. When your component renders, returns an object from Apollo Client that contains , , and properties you can use to render your UI.

Let's look at an example. First, we'll create a GraphQL query named . Remember to wrap query strings in the function to parse them into query documents:

index.js

Next, we'll create a component named . Inside it, we'll pass our query to the hook:

index.js

As our query executes and the values of , , and change, the component can intelligently render different UI elements according to the query's state:

  • As long as is (indicating the query is still in flight), the component presents a notice.
  • When loading is and there is no , the query has completed. The component renders a dropdown menu that's populated with the list of dog breeds returned by the server.

When the user selects a dog breed from the populated dropdown, the selection is sent to the parent component via the provided function.

In the next step, we'll associate the dropdown with a more sophisticated query that uses GraphQL variables.

Caching query results

Whenever Apollo Client fetches query results from your server, it automatically caches those results locally. This makes subsequent executions of the same query extremely fast.

To see this caching in action, let's build a new component called . accepts a prop called that reflects the current value of the dropdown menu in our component:

index.js

Notice that we're providing a configuration option () to the hook this time. The option is an object that contains all of the variables we want to pass to our GraphQL query. In this case, we want to pass the currently selected from the dropdown.

Select from the dropdown to see its photo appear. Then switch to another breed, and then switch back to . You'll notice that the bulldog photo loads instantly the second time around. This is the Apollo cache at work!

Next, let's learn some techniques for ensuring that our cached data is fresh.

Updating cached query results

Sometimes, you want to make sure that your query's cached data is up to date with your server's data. Apollo Client supports two strategies for this: polling and refetching.

Polling

Polling provides near-real-time synchronization with your server by executing your query periodically at a specified interval. To enable polling for a query, pass a configuration option to the hook with an interval in milliseconds:

index.js

By setting to 500, we fetch the current breed's image from the server every 0.5 seconds. Note that if you set to , the query does not poll.

You can also start and stop polling dynamically with the and functions that are returned by the hook.

Refetching

Refetching enables you to refresh query results in response to a particular user action, as opposed to using a fixed interval.

Let's add a button to our component that calls our query's function whenever it's clicked.

You can optionally provide a new object to the function. If you don't (as is the case in the following example), the query uses the same variables that it used in its previous execution.

index.js

Click the button and notice that the UI updates with a new dog photo. Refetching is an excellent way to guarantee fresh data, but it introduces some complexity with loading state. In the next section, we'll cover strategies for handling complex loading and error state.

Providing new variables to

You call with a new set of variables like so:

If you provide new values for some of your original query's variables but not all of them, uses each omitted variable's original value.

Inspecting loading states

We've already seen that the hook exposes our query's current loading state. This is helpful when a query first loads, but what happens to our loading state when we're refetching or polling?

Let's return to our refetching example from the previous section. If you click the refetch button, you'll see that the component doesn't re-render until the new data arrives. What if we want to indicate to the user that we're refetching the photo?

The hook's result object provides fine-grained information about the status of the query via the property. To take advantage of this information, we set the option to so our query component re-renders while a refetch is in flight:

index.js

Enabling this option also ensures that the value of updates accordingly, even if you don't want to use the more fine-grained information provided by the property.

The property is a enum that represents different loading states. Refetch is represented by , and there are also values for polling and pagination. For a full list of all the possible loading states, check out the source.

To view a complete version of the app we just built, check out the CodeSandbox here.

Inspecting error states

You can customize your query error handling by providing the configuration option to the hook. The default value is , which tells Apollo Client to treat all GraphQL errors as runtime errors. In this case, Apollo Client discards any query response data returned by the server and sets the property in the result object to .

If you set to , does not discard query response data, allowing you to render partial results.

For more information, see Handling operation errors.

Manual execution with

When React renders a component that calls , Apollo Client automatically executes the corresponding query. But what if you want to execute a query in response to a different event, such as a user clicking a button?

The hook is perfect for executing queries in response to events besides component rendering. Unlike with , when you call , it does not immediately execute its associated query. Instead, it returns a query function in its result tuple that you call whenever you're ready to execute the query.

Here's an example:

index.js

The first item in 's return tuple is the query function, and the second item is the same result object returned by .

As shown above, you can pass options to the query function just like you pass them to itself. If you pass a particular option to both, the value you pass to the query function takes precedence. This is a handy way to pass default options to and then customize those options in the query function.

For a full list of supported options, see the API reference.

Setting a fetch policy

By default, the hook checks the Apollo Client cache to see if all the data you requested is already available locally. If all data is available locally, returns that data and doesn't query your GraphQL server. This policy is Apollo Client's default fetch policy.

You can specify a different fetch policy for a given query. To do so, include the option in your call to :

You can also specify a query's . If you do, is used for the query's first execution, and is used to determine how the query responds to future cache updates:

For example, this is helpful if you want a query to always make an initial network request, but you're comfortable reading from the cache after that.

Supported fetch policies

NameDescription

Apollo Client first executes the query against the cache. If all requested data is present in the cache, that data is returned. Otherwise, Apollo Client executes the query against your GraphQL server and returns that data after caching it.

Prioritizes minimizing the number of network requests sent by your application.

This is the default fetch policy.

Apollo Client executes the query only against the cache. It never queries your server in this case.

A query throws an error if the cache does not contain data for all requested fields.

Apollo Client executes the full query against both the cache and your GraphQL server. The query automatically updates if the result of the server-side query modifies cached fields.

Provides a fast response while also helping to keep cached data consistent with server data.

Apollo Client executes the full query against your GraphQL server, without first checking the cache. The query's result is stored in the cache.

Prioritizes consistency with server data, but can't provide a near-instantaneous response when cached data is available.

Similar to , except the query's result is not stored in the cache.

Uses the same logic as , except this query does not automatically update when underlying field values change. You can still manually update this query with and .

API

Supported options and result fields for the hook are listed below.

Most calls to can omit the majority of these options, but it's useful to know they exist. To learn about the hook API in more detail with usage examples, see the API reference.

Options

The hook accepts the following options:

Name /
Type
Description

Operation options

A GraphQL query string parsed into an AST with the template literal.

Optional for the hook, because the query can be provided as the first parameter to the hook. Required for the component.

An object containing all of the GraphQL variables your query requires to execute.

Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.

Specifies how the query handles a response that returns both GraphQL errors and partial results.

For details, see GraphQL error policies.

The default value is , meaning that the query result includes error details but not partial results.

A callback function that's called when your query successfully completes with zero errors (or if is and partial data is returned).

This function is passed the query's result .

A callback function that's called when the query encounters one or more errors (unless is ).

This function is passed an object that contains either a object or a array, depending on the error(s) that occurred.

If , the query is not executed. Not available with .

This property is part of Apollo Client's React integration, and it is not available in the core API.

The default value is .

The name of your component to be displayed in the React Developer Tools.

The default value is .

Networking options

Specifies the interval (in milliseconds) at which the query polls for updated results.

The default value is (no polling).

If , the in-progress query's associated component re-renders whenever the network status changes or a network error occurs.

The default value is .

If you're using Apollo Link, this object is the initial value of the object that's passed along your link chain.

Pass to skip executing the query during server-side rendering.

The instance of to use to execute the query.

By default, the instance that's passed down via context is used, but you can provide a different instance here.

Caching options

Specifies how the query interacts with the Apollo Client cache during execution (for example, whether it checks the cache for results before sending a request to the server).

For details, see Setting a fetch policy.

The default value is .

Specifies the to use for all executions of this query after this execution.

For example, you can use this to switch back to a fetch policy after using or for a single execution.

If , the query can return partial results from the cache if the cache doesn't contain results for all queried fields.

The default value is .

Deprecated options

Deprecated. If , causes a query if the query result is detected as partial. Setting this option is unnecessary in Apollo Client 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.

The default value is .

Result

After being called, the hook returns a result object with the following properties. This object contains your query result, plus some helpful functions for refetching, dynamic polling, and pagination.

Name /
Type
Description

Operation data

An object containing the result of your GraphQL query after it completes.

This value might be if a query results in one or more errors (depending on the query's ).

An object containing the result from the most recent previous execution of this query.

This value is if this is the query's first execution.

If the query produces one or more errors, this object contains either an array of or a single . Otherwise, this value is .

For more information, see Handling operation errors.

An object containing the variables that were provided for the query.

Network info

If , the query is still in flight and results have not yet been returned.

A number indicating the current network state of the query's associated request. See possible values.

Used in conjunction with the option.

The instance of Apollo Client that executed the query.

Can be useful for manually executing followup queries or writing data to the cache.

If , the associated lazy query has been executed.

This field is only present on the result object returned by .

Helper functions

A function that enables you to re-execute the query, optionally passing in new .

To guarantee that the refetch performs a network request, its is set to (unless the original query's is or , which also guarantee a network request).

See also Refetching.

A function that helps you fetch the next set of results for a paginated list field.

A function that instructs the query to begin re-executing at a specified interval (in milliseconds).

A function that instructs the query to stop polling after a previous call to .

A function that enables you to execute a subscription, usually to subscribe to specific fields that were included in the query.

This function returns another function that you can call to terminate the subscription.

A function that enables you to update the query's cached result without executing a followup GraphQL operation.

Next steps

Now that you understand how to fetch data with the hook, learn how to update your data with the hook!

After that, learn about some other handy Apollo Client features:

Edit on GitHub

Sours: https://www.apollographql.com/docs/react/data/queries/

Query graphql react

tannerlinsley / react-query Public

  • Huge bundle size improvement: Probably lost more than 20 KB in bundle size. (Caveat: In my usage, I removed and in runtime, by processing things at build time using graphq-code-generator to parse and convert documents to strings and extracting the operation names and then generating strongly typed hooks like (had to write a custom plugin, very similar to apollo's).

  • Caching mechanism is much better for me to reason about and control. With apollo, I would often be stuck figuring out how to make sure my queries are being refreshed when necessary with things like page transitions after mutations.

  • Error handling: I could never properly understand the error handling part of apollo with mutations, when would it throw vs when would it return an object. I could control things better with since I wrote the graphql error throwing side. Still some polish is required in the graphql code here.

  • No normalized caching: One of Apollo's big value proposition is normalized caching. I didn't have a lot of use of it, since most of my data structures across components were not really overlapping. I don't miss it in my usage right now.

  • Server-side rendering: Apollo has first class support with their function which traverses the tree and sees what all data is needed, and fetches it on the server side. Needs to be setup at once place only (HOC). With , there is the option. It's simple to use but not as powerful as apollo's options. We moved to a JAMStack strategy and so this wasn't a major pain point for us.

  • Devtools: I like having the console open, and still having the devtools available to me. With apollo have to switch between tabs.

  • Refresh on focus: I really like this feature and wished I had it in apollo.

  • Lazy queries: Apollo has this hook called that has a like signature for load queries lazily. I added a option to to the same effect. The query is not fetched till its . It conditionally adds a falsy value to the query key passed down to .

  • API for refetching queries: After mutations occur, other queries need to be refetched and apollo has an option called which would accept an array of queries (operation names only) to refetch after mutation. Right now we are calling in the callback, but can probably provide a similar API.

  • Sours: https://github.com/tannerlinsley/react-query/discussions/301
    All About React Query (with Tanner Linsley) — Learn With Jason

    TypeScript React-Query

    Usage Requirements

    In order to use this GraphQL Codegen plugin, please make sure that you have GraphQL operations ( / / and ) set as in your .

    Without loading your GraphQL operations (query, mutation, subscription and fragment), you won't see any change in the generated output.

    This plugin generates Hooks with TypeScript typings.

    It extends the basic TypeScript plugins: , - and thus shares a similar configuration.

    Installation

    typescript-react-query plugin version

    Using

    API Reference

    type:

    Customize the fetcher you wish to use in the generated file. React-Query is agnostic to the data-fetcing layer, so you should provide it, or use a custom one.

    The following options are available to use:

    • 'fetch' - requires you to specify endpoint and headers on each call, and uses to do the actual http call.
    • : hardcode your endpoint and fetch options into the generated output, using the environment method. You can also use as endpoint or header value.
    • - You can use custom fetcher method that should implement the exported interface. Example: .
    • : Will generate each hook with argument, where you should pass your own (created from ).

    type: default:

    For each generate query hook adds field with a corresponding GraphQL query. Useful for .

    Usage Examples

    type: default:

    For each generate query hook adds getKey(variables: QueryVariables) function. Useful for cache updates.

    Usage Examples

    type: default:

    For each generate query hook addds field with a corresponding GraphQL query using the fetcher. It is useful for and .

    Usage Examples

    type: default:

    Changes the default "TError" generic type.

    type: default:

    Set this configuration to if you wish to make sure to remove duplicate operation name suffix.

    type: default:

    Set this configuration to if you wish to disable auto add suffix of operation name, like , , , .

    type: default: ``

    Adds a suffix to generated operation result type names

    type: default: ``

    Changes the GraphQL operations variables prefix.

    type: default:

    Changes the GraphQL operations variables suffix.

    type: default: ``

    Changes the GraphQL fragments variables prefix.

    type: default:

    Changes the GraphQL fragments variables suffix.

    type: default:

    If you are using , you can set this to to apply document optimizations for your GraphQL document. This will remove all "loc" and "description" fields from the compiled document, and will remove all empty arrays (such as , and ).

    type: default:

    This config adds PURE magic comment to the static variables to enforce treeshaking for your bundler.

    type: default:

    If set to true, it will enable support for parsing variables on fragments.

    type: default:

    Makes scalars strict.

    If scalars are found in the schema that are not defined in an error will be thrown during codegen.

    Usage Examples

    type: default:

    Allows you to override the type that unknown scalars will have.

    Usage Examples

    type:

    Extends or overrides the built-in scalars and custom GraphQL scalars to a custom type.

    type: default:

    Allow you to override the naming convention of the output. You can either override all namings, or specify an object with specific custom naming convention per output. The format of the converter must be a valid . Allowed values for specific output are: , . You can also use "keep" to keep all GraphQL names as-is. Additionally you can set to if you want to override the default behavior, which is to preserves underscores.

    Available case functions in are , , , , , , , , , , , , , , , , , and See more

    type: default: ``

    Prefixes all the generated types.

    Usage Examples

    type: default: ``

    Suffixes all the generated types.

    Usage Examples

    type: default:

    Does not add __typename to the generated types, unless it was specified in the selection set.

    Usage Examples

    type: default:

    Automatically adds field to the generated types, even when they are not specified in the selection set, and makes it non-optional

    Usage Examples

    type: default:

    Removes fragment duplicates for reducing data transfer. It is done by removing sub-fragments imports from fragment definition Instead - all of them are imported to the Operation node.

    type: default:

    Whether fragment types should be inlined into other operations. "inline" is the default behavior and will perform deep inlining fragment types within operation type definitions. "combine" is the previous behavior that uses fragment type references without inlining the types (and might cauuse issues with deeply nested fragment that uses list types).

    Usage Examples#

    Note: all generated hooks are just wrappers around original functions. This codegen plugin just burns the generated TypeScript types into the operation, and provides flexibility to choose your .

    Using default #

    By default, this plugin will generate a based on the environment global definition.

    To use the generate hooks, import it, and then specify the endpoint and optionally :

    Using with Codegen configuration#

    If you wish to avoid specifying and on each hook usage, you can specify those in the file:

    And if you wish to have more control over the value, or even provide it in runtime, you can use environment variables:

    You can even use a custom variable from your code, and add custom imports with plugin:

    The generated hooks doesn't require you to specify anything, you can just use it as-is:

    Using #

    If you are using , you can set to , and then the generated React Hook will expect you to pass the instance (created by library).

    And the, while using, provide your instance:

    Using Custom Fetcher#

    If you wish to create a custom fetcher, you can provide your own function as a Mapper string (). Codegen will take care of importing it and use it as a fetcher.

    As a shortcut, the property may also directly contain the function as a mapper string:

    Codegen will use , and you can just use the hook directly:

    Depending on the property, your should be in the following signature:

    Usage example ()#

    Usage example ()#

    Note: The return value is an async function, with no params, that returns a with the actual data.

    Sours: https://graphql-code-generator.com/docs/plugins/typescript-react-query

    Now discussing:

    How to use React Query with React and GraphQL

    React Query is a library that provides a set of hooks for fetching, caching, and updating data in your React applications. In this tutorial, we will be looking at React Query and learning how to use it in a React and GraphQL app.

    What is React Query?

    React Query (RQ) is a performant and powerful data synchronization library for React apps. It provides a collection of hooks for fetching and managing data. It is backend agnostic, which means you can use REST, GraphQL, or whatever APIs you like, RQ doesn’t care. React Query handles caching, background updates, and stale data out of the box with zero-configuration. The caching layer of RQ is powerful and minimal effort to configure.

    React Query makes state managing easy because it allows you to fetch, mutate and cache data with almost no hassle. And can also be customized for more advanced use cases. While React Query does a lot for you, it’s not a complete replacement for client-state management libraries because RQ can’t handle UI state (state for controlling the interactive parts of our app); it’s a library for fetching and synchronization data.

    However, RQ is designed to replace the boilerplate code and related wiring used to manage cache data in your client-state and replaces it with just a few lines of code. RQ has to manage asynchronous operations between your server and client and use Redux, MobX, Zustand, or even React Context to handle the UI state. This way, you will get a simplified app logic and delivers a snappy experience to your users with less code.

    What we’re building

    In this guide, we will be building a Blog app using React, React Query, and GraphQL. We will retrieve the data from the TakeShape GraphQL API. Let’s get started!

    Setting up

    Before we craft up a new React app, we need to sign up for an account on TakeShape (it’s free) then create a new project to get a GraphQL API to play with. After you create an account and create a read-only API key, open your command-line interface and run the following:

    This command will create a new React app for us. Next, we need to install a couple of libraries. Browse to the project root and do the following:

    Here’s what each of the libraries you are installing does:

    • allows interacting with the GraphQL API and retrieve the data.
    • enables routing in our app.
    • is a dependency for .
    • allows fetching data from a GraphQL backend.
    • helps render Markdown in a React app.

    With the dependencies installed, we can get our hands dirty and see React Query in action.

    Folder structure

    Structure your project as follows:

    Take special note of the file. It is a custom hook that uses RQ to retrieve the data from the TakeShape GraphQL API. This file is where the magic happens; it helps interact with the API to fetch the blog posts. You can alternatively use the RQ hooks in your components, but it’s nice to have a custom hook to avoid repeating ourselves.

    Next, let’s configure our app to use React Query.

    Setting up React Query

    In order to use the hooks of RQ to interact with our GraphQl API, we need to wrap our top-level app component with the RQ library query provider.

    Using React Query

    In , we start by importing the hook and graphl-request. Next, we declare the constant with the credentials provided by TakeShape. For each request, we need to include an authorization header with the API key from TakeShape in order to authenticate to the GraphQL API . Using allows us to set the API key on each request.

    To get all blog posts from the API, we use the function. The hook expects a key () and a GraphQL query. The hook can receive more options, but for this example, we just need these two. Once the fetch is done, we return the data. React Query will append some data to the returned value, which allows handling loading and error states.

    Next, , receives the of the post to fetch. To pass in the to the GraphQL query, we need to add it as a second argument to the method. With this, the data is fetched and then returned.

    The custom hook is ready to use. Let’s create the React components and rely on the hook to retrieve the data.

    Creating the components

    This component is responsible for the display of a blog post preview. It receives the object as a parameter and then shows it accordingly.

    is a template to display a blog post. The is pulled out from the router params and then passed in to the hook. With this, we can now get the post using its . It returns the data and some states provided by RQ to handle the case when something went wrong.

    Showing the blog posts

    In , we import the custom hook and use it to get all blog posts from the API. Then loop through the response data and display the posts using the component.

    We are now ready to test our example app in the browser. Open the project directory in your CLI and run:

    If everything works as it should, the app will be up and running here: .

    Awesome! Our Blog app is looking nice.

    React Query comes with dedicated devtools. It helps visualize all of the inner workings of React Query and will likely save you hours of debugging. To enable it, we need to enable it in .

    Import from and add it as a child component of the component. That’s it! The devtools are ready to use. Let’s try it in the browser.

    Once you click on the React Query logo, the devtools will pop up with its neat features. Enjoy!

    You can find the finished project in this CodeSandbox. Thanks for reading!

    Conclusion

    React Query is a useful library for managing asynchronous operations between your server and client. It continues to gain traction and is trusted in production by large companies such as Google, Facebook, Amazon, and Microsoft. Folks are using it to simplify their state management because it has great caching strategies, can synchronize and updates server state, and has less boilerplate. RQ is a go-to for your next project that requires remote data fetching.

    Sours: https://www.takeshape.io/articles/how-to-use-react-query-with-react-and-graphql/


    936 937 938 939 940