[Graphql] Apollo Client Example

Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. Use it to fetch, cache, and modify application data, all while automatically updating your UI.

Apollo Client helps you structure code in an economical, predictable, and declarative way that's consistent with modern development practices. The core @apollo/client library provides built-in integration with React, and the larger Apollo community maintains integrations for other popular view layers.

 

On client side, we still keep the data inside our memory, and we want to connect Graphql API, so that we use @apollo/client 

 

Config setup:

复制代码
const React = require("react");
const {
  ApolloClient,
  ApolloProvider,
  HttpLink,
  InMemoryCache,
} = require("@apollo/client");
const wrapRootElement = require("./wrap-root-element");

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: "https://gxxxxxxxxxx.netlify.app/.netlify/functions/graphql",
  }),
});

exports.wrapRootElement = ({ element }) => (
  <ApolloProvider client={client}>
    {wrapRootElement({ element })}
  </ApolloProvider>
);
复制代码

 

 

Example:

复制代码
import React, { useContext, useReducer, useRef } from "react";
import { IdentityContext } from "../../identity-context";
import {
  Container,
  Flex,
  Button,
  Input,
  Label,
  NavLink,
  Checkbox,
} from "theme-ui";
import { Link } from "@reach/router";
import { gql, useMutation, useQuery } from "@apollo/client";

const ADD_TODO = gql`
  mutation AddTodo($text: String!) {
    addTodo(text: $text) {
      id
    }
  }
`;

const UPDATE_TODO_DONE = gql`
  mutation UpdateTodoDone($id: ID!) {
    updateTodoDone(id: $id) {
      text
      done
    }
  }
`;

const GET_TODOS = gql`
  query GetTodos {
    todos {
      id
      text
      done
    }
  }
`;

const Dash = () => {
  const { user, identity: netlifyIdentity } = useContext(IdentityContext);
  const inputRef = useRef();
  const [addTodo] = useMutation(ADD_TODO);
  const [updateTodoDone] = useMutation(UPDATE_TODO_DONE);
  const { loading, error, data, refetch } = useQuery(GET_TODOS);
  return (
    <Container>
      <Flex as="nav">
        <NavLink as={Link} to="/" p={2}>
          Home
        </NavLink>
        <NavLink as={Link} to={"/app"} p={2}>
          Dashboard
        </NavLink>
        {user && (
          <NavLink
            href="#!"
            p={2}
            onClick={() => {
              netlifyIdentity.logout();
            }}
          >
            Log out {user.user_metadata.full_name}
          </NavLink>
        )}
      </Flex>
      <Flex
        as="form"
        onSubmit={async (e) => {
          e.preventDefault();
          await addTodo({ variables: { text: inputRef.current.value } });
          inputRef.current.value = "";
          await refetch();
        }}
      >
        <Label sx={{ display: "flex" }}>
          <span>Add&nbsp;Todo</span>
          <Input ref={inputRef} sx={{ marginLeft: 1 }} />
        </Label>
        <Button sx={{ marginLeft: 1 }}>Submit</Button>
      </Flex>
      <Flex sx={{ flexDirection: "column" }}>
        {loading ? <div>loading...</div> : null}
        {error ? <div>{error.message}</div> : null}
        {!loading && !error && (
          <ul sx={{ listStyleType: "none" }}>
            {data.todos.map((todo, i) => (
              <Flex
                as="li"
                key={todo.id}
                onClick={async () => {
                  await updateTodoDone({ variables: { id: todo.id } });
                  await refetch();
                }}
              >
                <Checkbox checked={todo.done} />
                <span>{todo.text}</span>
              </Flex>
            ))}
          </ul>
        )}
      </Flex>
    </Container>
  );
};

export default Dash;
复制代码

 

To keep data in order (client and server), we use 'async/await' to wait fetch request to be resolved first, then we call 'refetch()' to get latest data to get latest data from backend. 

posted @   Zhentiw  阅读(76)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-02-25 [Unit testing Angular] Complete component code
2020-02-25 [Javascript] Objects and Functions
2020-02-25 [HTML5] Element id binding
2019-02-25 [Functional Programming] Working with two functors(Applicative Functors)-- Part1 --.ap
2019-02-25 [React] Preventing extra re-rendering with function component by using React.memo and useCallback
2018-02-25 [ES2018] Two ways to write for-await-of
2016-02-25 [RxJS] Using Observable.create for fine-grained control
点击右上角即可分享
微信分享提示