fetch data with graphql in javascript

To fetch data with GraphQL in JavaScript, you can use a library such as Apollo Client. Here's an example of how to use Apollo Client to fetch data using GraphQL in JavaScript:

First, install Apollo Client by running:

npm install apollo-client graphql-tag

Then, create a client instance:

index.tsx
import ApolloClient from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = createHttpLink({
  uri: 'your-graphql-api-url',
});

const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache(),
});
305 chars
13 lines

Next, define your GraphQL query:

index.tsx
import gql from 'graphql-tag';

const GET_USERS = gql`
  {
    users {
      id
      name
      email
    }
  }
`;
116 chars
12 lines

Finally, fetch the data using the client:

index.tsx
client
  .query({
    query: GET_USERS,
  })
  .then(result => console.log(result));
85 chars
6 lines

This will log the result of the query to the console. You can also handle errors and loading states with Apollo Client.

gistlibby LogSnag