Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

how to use graphql api in react

import React from "react";
import { request, gql } from "graphql-request";
import { useQuery } from "react-query";

const endpoint = "https://api.spacex.land/graphql/";
const FILMS_QUERY = gql`
  {
    launchesPast(limit: 10) {
      id
      mission_name
    }
  }
`;

export default function App() {
  const { data, isLoading, error } = useQuery("launches", () => {
    return request(endpoint, FILMS_QUERY);
  });

  if (isLoading) return "Loading...";
  if (error) return <pre>{error.message}</pre>;

  return (
    <div>
      <h1>SpaceX Launches</h1>
      <ul>
        {data.launchesPast.map((launch) => (
          <li key={launch.id}>{launch.mission_name}</li>
        ))}
      </ul>
    </div>
  );
}
Comment

react-query for graphql

import { useContext, useState } from "react";
import { Button, Grid } from "@mui/material";
import request, { gql } from "graphql-request";
import { formatISO, subMonths, endOfToday, startOfDay, endOfDay } from "date-fns";
import { UserContext } from "../contexts/user.context";
import { GRAPHQL_ENDPOINT } from "../realm/constants";
import PageContainer from "../components/PageContainer.component";
import CustomDatePicker from "../components/CustomDatePicker.component";
import ModeAnalytics from "../components/ModeAnalytics.component";
import CategoryAnalytics from "../components/CategoryAnalytics.component";
import { useQuery } from "react-query";

const Analytics = () => {
  const today = endOfToday();
  const oneMonthAgo = subMonths(today, 6);
  const [fromDate, setFromDate] = useState(oneMonthAgo);
  const [toDate, setToDate] = useState(today);

  const { user } = useContext(UserContext);

  const getAnalyticsQuery = gql`
    query getAnalytics($query: Filter!) {
      modeAnalytics(input: $query) {
        modes {
          amount
          mode
        }
      }
      categoryAnalytics(input: $query) {
        categories {
          amount
          category
        }
      }
    }
  `;

  const queryVariables = { query: { from: formatISO(startOfDay(fromDate)), to: formatISO(endOfDay(toDate)) } };

  const headers = { Authorization: `Bearer ${user._accessToken}` };

  const loadAnalytics = async () => request(
    GRAPHQL_ENDPOINT,
    getAnalyticsQuery,
    queryVariables,
    headers
  );

  // Again, we are replacing useEffect and useState with useQuery.
  // The data is already managed by the useQuery hook and we will just display 
  // component when it's fetched, until then we will display a loading indicator.
  const { data, error, isLoading, refetch } = useQuery("analytics", loadAnalytics);

  if (isLoading) return "Loading Analytics Data";

  if (error) return error;

  const { modeAnalytics: { modes }, categoryAnalytics: { categories } } = data;

  return (
    <PageContainer>
      <h1>Analytics Home</h1>
      <CustomDatePicker label="From" value={fromDate} onChange={setFromDate} style={{ marginRight: "2rem" }} />
      <CustomDatePicker label="To" value={toDate} onChange={setToDate} style={{ marginRight: "2rem" }} />
      <Button onClick={refetch} variant="contained" style={{ margin: "0 auto" }} size="large">Refresh</Button>
      {(modes && categories) && <Grid container spacing={3}>
        <Grid item xs={12} md={6}>
          <ModeAnalytics data={modes} />
        </Grid>
        <Grid item xs={12} md={6}>
          <CategoryAnalytics data={categories} />
        </Grid>
      </Grid>}
    </PageContainer>
  );
}

export default Analytics;
Comment

react js and graphql integration

1
2
3
npx create-react-app my-graphql-react-project
cd my-graphql-react-project
yarn add @apollo/client graphql
Comment

install graphql react

npm install graphql-react react
Comment

PREVIOUS NEXT
Code Example
Javascript :: dropzone remove error file 
Javascript :: number to float js 
Javascript :: link tag react 
Javascript :: let var 
Javascript :: lastindexof() javascript 
Javascript :: jquery select option value selected 
Javascript :: prependchild javascript 
Javascript :: how to change icon from play to pause in javascript 
Javascript :: axios forward 
Javascript :: javascript createelement innerhtml 
Javascript :: geojson 
Javascript :: check a date is between two dates in javascript 
Javascript :: logic operators in js 
Javascript :: js add html element 
Javascript :: Navigator operation requested with a context that does not include a Navigator. 
Javascript :: javascript convert input to lowercase 
Javascript :: Substring in Javascript using substring 
Javascript :: uncheck multiple checkboxes javascript 
Javascript :: javascript rect 
Javascript :: nvalid response body while trying to fetch https://registry.npmjs.org/scheduler: Socket timeout 
Javascript :: area of a triangle javascript 
Javascript :: outer click on div hide div in jqeury 
Javascript :: dispatch two actions in redux 
Javascript :: javascript date set hours minutes seconds to 0 
Javascript :: react native data map is not a function 
Javascript :: javascript array.from 
Javascript :: add even numbers recursion js 
Javascript :: email regex javascript 
Javascript :: getting te value of select multiple value 
Javascript :: node js do request 
ADD CONTENT
Topic
Content
Source link
Name
4+9 =