Home > database >  How to query graphql in react typescript
How to query graphql in react typescript

Time:06-21

So I have set up a graphql and can use it in Postmen successfully.

It looks like this

query listByName($name: String!) {
    listByName(name: $name) {
        id
        name
        sortOrder
    }
}

and this as my variable {"name": "Products"}

The output is the wanted one, but how do I now approach using this? How do I fetch it in the frontend and display for example a simple list of all lists with the name Products.

CodePudding user response:

There are many tools for that task. GraphQL codegen does amazing job - you input the schema (by file path or url) and it generates ready-to-use react hooks, all typed, out of the box. https://www.graphql-code-generator.com/docs/guides/react

CodePudding user response:

I like to use grapql-request for simple usages. Then you could use useState to hold your response data and useEffect to trigger your request:

import { useState, useEffect } from 'react'
import { request, gql } from 'graphql-request'

const query = gql`
  query listByName($name: String!) {
    listByName(name: $name) {
        id
        name
        sortOrder
    }
  }
`;

const SomeComponent = ({ name }) => {
    const [data, setData] = useState();

    useEffect(() => {
        // Keep track if component is still mounted
        let active = true;

        // Make the request
        request('https://api.graph.cool/simple/v1/movies', query, { name }).then((data) => {
            if (!active) {
                // If `active` isn't truthy anymore, the component was unmounted while we load
                // the data and we are not able to update its state, so abort here.
                return;
            }

            setData(data);
        });

        return () => {
            // When the component is unmoundted, we set the active flag to false
            active = false;
        }
    }, [name]);

    if (!data) {
        <div>Loading data</data>
    }

    return (
        <ul>
            {data.listByName.map(item => (
                <li>{item.name}</li>
            ))}
        </ul>
    );
};

In the example I used a simple flag for only setting the data if the comonent is still mounted. In a more complex application I would use an AbortController to cancel the actual request.

  • Related