标签: react-apollo

如何仅在用户身份验证后设置 Apollo 客户端?

我对如何构建我的 React/GraphQL (Apollo) 应用程序感到有点困惑,因为在用户验证/登录之前不应建立连接。

目前我有这个:

class App extends Component {
  render() {
    return (
      <ApolloProvider client={client}>
        <Provider store={store}>
          <Router>
            <div>
              <ul>
                <li><Link to="/">Home</Link></li>
                <li><Link to="/login">Log In</Link></li>
                <li><Link to="/signup">Sign Up</Link></li>
              </ul>
              <AuthenticatedRoute exact path="/" component={HomePage} />
              <Route path="/login" component={LoginPage} />
              <Route path="/signup" component={SignupPage} />
            </div>
          </Router>
        </Provider>
      </ApolloProvider>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

这是网络接口的创建:

const networkInterface = createNetworkInterface({
  uri: process.env.NODE_ENV === 'development'
    ? 'http://localhost:3000/graphql'
    : 'TBD',
});

networkInterface.use([
  {
    applyMiddleware(req, next) {
      if (!req.options.headers) {
        req.options.headers = {}; // Create the header object …
Run Code Online (Sandbox Code Playgroud)

apollo reactjs graphql react-apollo apollo-client

7
推荐指数
1
解决办法
3441
查看次数

Apollo 客户端写入查询未更新 UI

我们正在使用 Apollo Client 构建一个离线的第一个 React Native 应用程序。目前我正在尝试在离线时直接更新 Apollo Cache 以乐观地更新 UI。由于我们离线,我们不会尝试在连接为“在线”之前触发突变,但希望 UI 在仍处于离线状态时触发突变之前反映这些更改。我们正在使用来自http://dev.apollodata.com/core/read-and-write.html#writequery-and-writefragment的 readQuery / writeQuery API 函数。并且能够通过 Reacotron 查看正在更新的缓存,但是,UI 不会更新此缓存更新的结果。

    const newItemQuantity = existingItemQty + 1;
    const data = this.props.client.readQuery({ query: getCart, variables: { referenceNumber: this.props.activeCartId } });
    data.cart.items[itemIndex].quantity = newItemQuantity;
    this.props.client.writeQuery({ query: getCart, data });
Run Code Online (Sandbox Code Playgroud)

javascript apollo reactjs react-native react-apollo

7
推荐指数
2
解决办法
7658
查看次数

React Apollo Client 不发送 cookie

我已经尝试按照 Apollo Client 上的说明将 cookie 与 graphql 请求一起发送,但是 express 服务器没有接收任何 cookie,当我检查请求时,它显示没有 cookie 与响应一起发送。

在此页面之后:

https://www.apollographql.com/docs/react/recipes/authentication.html

我的代码是

const link = createHttpLink({
  uri: 'http://localhost:3000/api/graphql',
  opts: {
    credentials: 'include',
  }
});

const client = new ApolloClient({
  link,
  cache: new InMemoryCache()
});
Run Code Online (Sandbox Code Playgroud)

我的设置非常简单,我只是在 localhost:3000 上使用 create-react-app 服务器,将 api 请求发送到 localhost:5000(快速 api 服务器)。我可以通过 localhost:3000 在其他路由上设置和检索 cookie,只有 Apollo Client 不发送它们。

cookies express react-apollo

7
推荐指数
1
解决办法
4944
查看次数

Apollo writeFragment不更新数据

在react-apollo 2.0.1中,我有一个如下所示的graphql类型:

type PagedThing {
  data: [Thing]
  total: Int
}
Run Code Online (Sandbox Code Playgroud)

在执行以下writeFragment时

  client.writeFragment({
    id,
    fragment: gql`
      fragment my_thing on Thing {
        status
      }
    `,
    data: {
      status
    }
  })
Run Code Online (Sandbox Code Playgroud)

缓存未更新,新数据未显示在UI上.还有什么需要做的吗?

PS:为了安全起见,我使用了片段匹配

编辑1:

我收到错误:

无法匹配片段,因为缺少__typename属性:{"status":"online"}

所以我将代码更改为:

client.writeFragment({
    id,
    fragment: gql`
      fragment my_thing on Thing {
        status
      }
    `,
    data: {
      __typename: 'Thing',
      status
    }
  })
Run Code Online (Sandbox Code Playgroud)

并且不会抛出任何错误,但更新仍然不会发生

caching graphql react-apollo

7
推荐指数
1
解决办法
2034
查看次数

在react-apollo中使用refetchQueries时使用现有变量

我正在使用postsConnection无限滚动查询。它包含诸如 之类的变量after。进行赞成突变后,我想refetchQueries......像这样

const upvote = await client.mutate({
      mutation: UPVOTE_MUTATION,
      variables: {
        postId: this.props.post.id
      },
      refetchQueries: [
        { query: POST_AUTHOR_QUERY }
      ]
    })
Run Code Online (Sandbox Code Playgroud)

上面的代码给出错误,因为POST_AUTHOR_QUERY接受很少的变量。这是该查询

export const POST_AUTHOR_QUERY = gql`
    query POST_AUTHOR_QUERY($authorUsername: String! $orderBy: PostOrderByInput $after: String){
        postsAuthorConnection(authorUsername: $authorUsername orderBy: $orderBy after: $after) {
                   ....
        }
    }
Run Code Online (Sandbox Code Playgroud)

我不想手动添加变量。变量已经存储在缓存中。使用时如何重复使用它们refetchQueries???

以下是我读过的有关此问题的一些资源

https://github.com/apollographql/react-apollo/issues/817

https://github.com/apollographql/apollo-client/issues/1900

javascript apollo graphql react-apollo prisma-graphql

7
推荐指数
2
解决办法
3290
查看次数

为什么在 api 工作正常的情况下,在fragment上使用apollo客户端查询会得到一个空对象?

我想获取动态类型的数据。为此,我在 graphql 查询中使用片段。Api 在 graphql Playground 中工作正常,但是当我尝试将它与 React-apollo 客户端集成时,它也给了我一个空对象以及警告!控制台中正在进行的启发式片段匹配。

当我使用 npm install 和 npm run start 时它也可以工作,但是当我切换到yarn install 和yarn run start 时它给了我一个错误。

我使用 IntrospectionFragmentMatcher 并将 fetchPolicy 设置为“缓存和策略”。

我还共享了用于客户端配置的 IntrospectionFragmentMatcher 的代码。

query GetContentSections($contentPageId: Int) {
  contentSection {
    searchContentSections(contentPageId: $contentPageId, status: [ACTIVE]) {
      id
      contentLayoutId
      sort
      sectionContainers {
        id
        sort
        snippets {
          id
          sort
          type: __typename
          ...quote
          ...text
          ...image
          ...video
          ...audio
          ...button
          ...popup
          ...map
          ...code
          ...app
        }
      }
    }
  }
}
fragment text on ContentSnippetTextType{
  text
}
fragment image on ContentSnippetImageType{
  assetId …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs graphql react-apollo apollo-client

7
推荐指数
1
解决办法
2254
查看次数

如何将 auth0 访问令牌添加到react-apollo

我正在尝试在 React js 中向 apollo 客户端添加授权令牌以让用户登录...

\n

索引.js

\n
import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { BrowserRouter as Router } from 'react-router-dom';\nimport { ThemeProvider } from 'react-jss';\nimport Theme from 'resources/theme';\nimport Routes from 'routes';\nimport './index.css';\nimport * as serviceWorker from './serviceWorker';\nimport { Auth0Provider } from "@auth0/auth0-react";\nimport 'bootstrap/dist/css/bootstrap.min.css';\nimport ReactNotification from 'react-notifications-component'\nimport './components/orders/fonts/NotoSansJP-Regular.otf'\nimport 'react-notifications-component/dist/theme.css'\nimport { ApolloProvider , ApolloClient, InMemoryCache } from '@apollo/client';\nimport { useAuth0 } from "@auth0/auth0-react";\n\n\nconst client = new ApolloClient({\nuri: process.env.REACT_APP_API_BACK ,\nheaders: {\n  Authorization: `Bearer ${accessToken}` // doesn\xe2\x80\x99t work \n },\n  cache: …
Run Code Online (Sandbox Code Playgroud)

apollo reactjs auth0 react-apollo apollo-client

7
推荐指数
1
解决办法
2307
查看次数

如何从查询中检索 Apollo 客户端中的日期字段作为日期而不是字符串?

使用以下 graphql:

scalar Date

type MyModel {
  id: ID!
  date: Date!
}

query MyModels {
  myModels {
    id
    date
  }
}

type Query {
  myModel: [MyModel!]
}
Run Code Online (Sandbox Code Playgroud)

和解析器:

import { DateTimeResolver } from 'graphql-scalars'
const resolvers = {
  // Scalars
  Date: DateTimeResolver,

  myModels: async () => {
    return await context.user.getMyModels()
  }
}
Run Code Online (Sandbox Code Playgroud)

我的查询返回date: "2021-02-07T06:58:51.009Z". 是否可以让 Apollo Client 将其转换为 Date 对象?

apollo graphql react-apollo apollo-client

7
推荐指数
1
解决办法
4586
查看次数

Apollo 客户端 - 使用 useLazyQuery 获取更多,变量不更新(用于偏移分页)

预期结果: 我们按照 apollo 文档(https://www.apollographql.com/docs/react/pagination/offset-based/)进行了分页实现。使用读取/合并函数 一旦我们调用 fetchMore 函数并手动更新变量,我们期望使用新变量调用读取函数。

Apollo 文档片段

实际结果: 我们无法使分页正常工作,数据已正确获取但未正确显示。显示不良是由于变量未更新造成的。“读取”函数始终接收原始查询的变量。

useEffect(() => {
    if (isDefined(fetchMore)) {
      fetchMore({
        variables: {
          offset:
            currentPage === 1
              ? (currentPage - 1) * total
              : (currentPage - 1) * total + 1,
          first: total,
          searchString: searchString
        }
      })
    } else {
      getData({
        variables: {
          offset: 0,
          first: total,
          searchString: searchString
        }
      })
    }    }, [currentPage, fetchMore, searchString, getData])
Run Code Online (Sandbox Code Playgroud)

我们还尝试手动更新变量,因为我们不使用 useQuery,而是使用 useLazyQuery。

 client
    .watchQuery({
      query: GET_REPORTS,
      variables: {
        offset: 0,
        first: total,
        searchString: searchString
      } …
Run Code Online (Sandbox Code Playgroud)

react-apollo apollo-client

7
推荐指数
1
解决办法
2465
查看次数

Apollo readQuery,从缓存中获取数据

我正在尝试从 Apollo 缓存获取数据。我知道数据在那里,因为在 Apollo 开发工具中指定的记录可用。在我的 React 应用程序中,我进行了简单的单击并设置了 Id,该 Id 随后传递给查询。结果client.readQuery(...)null. 我在旋转,因为不知道为什么。我使用的代码与文档中的代码完全相同。

这是一个查询:

export const RECRUIT_QUERY = gql`
  query Recruit($id: ID!) {
    Recruit(_id: $id) {
      _id
      firstName
    }
  }
`;
Run Code Online (Sandbox Code Playgroud)

组件中apollo hooks的使用:

const client = useApolloClient();
const recruit = client.readQuery({
  query: RECRUIT_QUERY,
  variables: { id: selectedId }
})
Run Code Online (Sandbox Code Playgroud)

阿波罗的配置:

export const client = new ApolloClient({
  link: concat(
    authMiddleware,
    new HttpLink({
      uri: process.env.REACT_APP_API_URL,
    }),
  ),
  cache: new InMemoryCache(),
});
Run Code Online (Sandbox Code Playgroud)

这是 apollo 商店预览: 在此输入图像描述

apollo graphql react-apollo apollo-client

7
推荐指数
1
解决办法
8628
查看次数