标签: react-apollo

在 Apollo 中提交表单后,如何从 useQuery hook 获取数据?

我在反应功能组件中有一个搜索状态。

  const [search, setSearch] = React.useState({
    orgName: "",
    repoName: ""
  });
Run Code Online (Sandbox Code Playgroud)

因此,当用户提交表单时。我需要从搜索对象中获取数据。我所做的是:

const handleSearch = (e) => {
        e.preventDefault();
        const {loading, data, error} = useQuery(SEARCH_REPO, {
            variables : {orgName : search.orgName, repoName: search.repoName}
        });
  };
Run Code Online (Sandbox Code Playgroud)

这违反了反应钩子第一规则。我得到的错误是hooks cannot be used in non react functional component. 那么,我该如何使用它呢?是否可以将 useQuery 放入 useEffect 挂钩中,该挂钩将在搜索对象更新时重新获取数据?

reactjs react-apollo

5
推荐指数
1
解决办法
6465
查看次数

fetchMore 如何向组件返回数据?

我正在尝试使用 React Apollo ( https://www.apollographql.com/docs/react/data/pagination/#cursor-based )来遵循基于光标的分页示例,但我正在努力解决我的组件如何渲染原始内容的问题data 获取新的(附加的) data

这是我们获取原始数据并将其传递给组件的方式:

const { data: { comments, cursor }, loading, fetchMore } = useQuery(
    MORE_COMMENTS_QUERY
);

<Comments
      entries={comments || []}
      onLoadMore={...}
/>
Run Code Online (Sandbox Code Playgroud)

我不确定该fetchMore功能是如何工作的。

onLoadMore={() =>
        fetchMore({
          query: MORE_COMMENTS_QUERY,
          variables: { cursor: cursor },
          updateQuery: (previousResult, { fetchMoreResult }) => {
            const previousEntry = previousResult.entry;
            const newComments = fetchMoreResult.moreComments.comments;
            const newCursor = fetchMoreResult.moreComments.cursor;

            return {
              // By returning `cursor` here, we update the `fetchMore` function
              // to the new cursor. …
Run Code Online (Sandbox Code Playgroud)

javascript apollo reactjs graphql react-apollo

5
推荐指数
2
解决办法
6247
查看次数

Apollo 客户端延迟刷新

Apollo Client v3React 实现中,我使用钩子来使用订阅。当我从订阅接收数据时,我想重新获取查询,但前提是查询之前已执行过并且位于缓存中。有办法实现这一点吗?

我首先进行惰性查询,然后在收到订阅数据时手动检查缓存,然后尝试执行惰性查询并重新获取。它可以工作,但只是感觉很笨重......

export const useMyStuffLazyRefetch = () => {
    const [refetchNeeded, setRefetchNeeded] = useState<boolean>(false);
    const client = useApolloClient();
    const [getMyStuff, { data, refetch }] = useLazyQuery<IStuffData>(GET_MY_STUFF);

    useEffect(() => {
        if (refetchNeeded) {
            setRefetchNeeded(false);
            refetch();
        }
    }, [refetchNeeded]);

    const refetchIfNeeded = async () => {
        const stuffData = client.cache.readQuery<IStuffData>({ query: GET_MY_STUFF });
        if (!stuffData?.myStuff?.length) return;
        getMyStuff();
        setRefetchNeeded(true);
    }

    return {
        refetchIfNeeded: refetchIfNeeded
    };
}
Run Code Online (Sandbox Code Playgroud)

reactjs graphql react-apollo apollo-client

5
推荐指数
1
解决办法
1万
查看次数

Apollo 客户端 3:查询在 Chrome 的“网络”选项卡中返回结果,但在我的应用程序中未定义

我正在使用 v3 获取一些数据@apollo/client。在Chrome的网络选项卡(http结果)中,我可以看到它返回数据和错误(我并不担心该错误,我现在知道为什么会这样。):

\n
{\n    data: {workItems: [,\xe2\x80\xa6]},\xe2\x80\xa6},\n    errors: [{message: "Error trying to resolve position."\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但是在我的应用程序中,data返回未定义。

\n

这是我的客户端配置:

\n
export const graphqlClient = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.from([\n        onError(({ graphQLErrors, networkError }) => {\n            if (graphQLErrors) {\n                graphQLErrors.forEach(error =>\n                    console.log(\n                        `[GraphQL error]: ${JSON.stringify(error, null, 2)}`\n                    )\n                )\n            }\n            if (networkError) {\n                console.log(`[Network error]: ${networkError}`)\n            }\n        }),\n        apolloLink\n    ])\n})\n
Run Code Online (Sandbox Code Playgroud)\n

我的查询:

\n
gql`\n    query WorkItems($ppm: String) {\n        workItems(where: { ppm: $ppm }) {\n            ...WorkItemKanban\n …
Run Code Online (Sandbox Code Playgroud)

react-apollo apollo-client

5
推荐指数
1
解决办法
2053
查看次数

Apollo MockedProvider 未返回预期数据

我写了一个调用 apollo 的钩子useQuery。这很简单:

使用决策者:

import { useState } from 'react';
import { useQuery, gql } from '@apollo/client';

export const GET_DECIDER = gql`
  query GetDecider($name: [String]!) {
    deciders(names: $name) {
      decision
      name
      value
    }
  }
`;

export const useDecider = name => {
  const [enabled, setEnabled] = useState(false);

  useQuery(GET_DECIDER, {
    variables: {
      name
    },
    onCompleted: data => {
      const decision = data?.deciders[0]?.decision;
      setEnabled(decision);
    },

    onError: error => {
      return error;
    }
  });

  return {
    enabled
  };
};
Run Code Online (Sandbox Code Playgroud)

我现在正在尝试测试它,但MockedProvider …

javascript apollo reactjs react-apollo apollo-client

5
推荐指数
2
解决办法
7714
查看次数

Apollo 客户端 MockedProvider:跳过加载状态

我使用 Apollo 设置了一个 React 应用程序,以拥有一个处理从网络加载数据的包装器组件,以便下面的每个组件都可以直接从 Apollo 缓存查询数据,而不必担心处理加载状态。因此,我的组件如下所示:

export const COUNT_OFF_ADAPTER_QUERY = gql`
  query CountOffAdapterQuery($vampId: ID!) {
    vamp(id: $vampId) @client {
      id
      countingOff
      countingOffStartTime
    }
  }
`;

export const CountOffAdapter: React.FC<{}> = () => {
  const vampId = useCurrentVampId();

  const {
    data: {
      vamp: { countingOff, countingOffStartTime }
    }
  } = useQuery<CountOffAdapterQuery>(COUNT_OFF_ADAPTER_QUERY, {
    variables: { vampId }
  });

  const prev = usePrevious({ countingOff, countingOffStartTime });

  const countOff = useCountOff();

  useEffect(() => {
    // Do react stuff
  }, [countOff, countingOff, prev]);

  return …
Run Code Online (Sandbox Code Playgroud)

typescript apollo react-apollo apollo-client

5
推荐指数
1
解决办法
1382
查看次数

Apollo GraphQL 客户端 + Next.JS 错误处理

该组件很好地呈现了错误状态,但异常在控制台中显示为未捕获,并且在浏览器的下一个开发中显示对话框。有没有办法处理预期错误来抑制这种行为?

import { useMutation, gql } from "@apollo/client";
import { useEffect } from "react";

const CONSUME_MAGIC_LINK = gql`
  mutation ConsumeMagicLink($token: String!) {
    consumeMagicLink(token: $token) {
      token
      member {
        id
      }
    }
  }
`;

export default function ConsumeMagicLink({ token }) {
  const [consumeMagicLink, { data, loading, error }] =
    useMutation(CONSUME_MAGIC_LINK);

  console.log("DATA", data, "loading:", loading, "error:", error);

  useEffect(() => {
    try {
      consumeMagicLink({ variables: { token } });
    } catch (e) {
      console.log(e);
    }
  }, []);

  var text = "Link has expired …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-apollo next.js apollo-client

5
推荐指数
1
解决办法
3262
查看次数

apollo-server-micro:响应缺少标头“access-control-allow-methods:POST”

在我的next.js应用程序中,我尝试配置 Apollo 端点:

import { ApolloServer, gql } from "apollo-server-micro";

// This data will be returned by our test endpoint. Not sure if I need id? https://apuyou.io/blog/serverless-graphql-apollo-server-nextjs
const tacos = {
  meat: [
    {
      type: 'Al Pastor',
      imgURL: 'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/190130-tacos-al-pastor-horizontal-1-1549571422.png?crop=0.668xw:1.00xh;0.175xw,0&resize=480:*'
    },
    {
      type: 'Barbacoa',
      imgURL: 'https://i2.wp.com/www.downshiftology.com/wp-content/uploads/2021/02/Barbacoa-Tacos-3.jpg'
    },
    {
      type: 'Chorizo',
      imgURL: 'https://www.seriouseats.com/thmb/-8LIIIObcZMUBy-9gXlMsHcaeMI=/610x458/filters:fill(auto,1)/__opt__aboutcom__coeus__resources__content_migration__serious_eats__seriouseats.com__recipes__images__2014__04__20140428-sloppy-joe-chorizo-taco-recipe-food-lab-lite-8-503212a07b0a4d499952ff40aed57694.jpg'
    },
  ],
  fish: [
    {
      type: 'Camaron',
      imgURL: 'https://juegoscocinarpasteleria.org/wp-content/uploads/2019/07/1563435179_315_Tacos-De-Camarones-Con-Crema-De-Cal-Y-Cilantro.jpg'
    },
    {
      type: 'Salmon',
      imgURL: 'https://www.cookingclassy.com/wp-content/uploads/2015/04/salmon-tacos-with-avocado-salsa4-srgb..jpg'
    },
    {
      type: 'Pulpo',
      imgURL: 'https://images.squarespace-cdn.com/content/v1/5710a8b3e707ebb8c58fea2c/1590075315244-QNXQE1LGPH06HV3EDF6B/tacos_34.jpg?format=1000w'
    },
  ],
  veggi: [
    {
      type: …
Run Code Online (Sandbox Code Playgroud)

apollo apollo-server react-apollo next.js

5
推荐指数
1
解决办法
2942
查看次数

在 React 中取消之前的待处理请求(带有 useQuery 的 Apollo 客户端)

我在搜索页面上有搜索框,因此当输入“继续”时,它会为每种类型发送多个请求。我使用去抖来处理这个问题,所以我的请求减少了,但现在我需要取消待处理的请求,并且只有最新的请求应该在那里

我尝试了一些方法,但它对我不起作用。

Apollo 客户端版本 - 3.3.21 React 版本 - 17.0.2 React-dom 版本 - 17.0.2 Node -16

我尝试过的方法

reactjs graphql react-apollo apollo-client

5
推荐指数
1
解决办法
4621
查看次数

5
推荐指数
1
解决办法
2238
查看次数