如何将QueryComponent与pollInterval和本地状态更改一起使用

时间:2019-02-15 13:35:42

标签: react-apollo apollo-client

我正在编写一个小型搜索应用程序,该应用程序通过RESTapi开始搜索。在搜索完成之前,api会以260状态代码或250(如果搜索完成)响应。 为此,我编写了带有查询组件的组件,该组件轮询RESTapi:

import React from 'react';
import gql from "graphql-tag";
import { Query } from "react-apollo";

export const GET_SEARCH_RESULTS = gql`
  query GetSearchResults($sid: String!) {
      getSearchResults(sid: $sid) {
          status,
          clusteredOffers { 
              id,
              bookingId,
              totalPrice
          }
      }
  }
`;

export default class extends React.PureComponent {
  client = null;

  updateStatus = (data) => {
    this.client.writeData({ data: { currentSearch: { status: 
data.getSearchResults.status, __typename: 'CurrentSearch' }} })
  };

  render() {
    const { sid } = this.props;

    return (
      <Query
        query={GET_SEARCH_RESULTS}
        variables={{ sid }}
        pollInterval={500}
        onCompleted={this.updateStatus}
      >
        {({ loading, error, data, stopPolling, client }) => {
          this.client = client;

          if (loading) return 'Loading...';
          if (error) return `Error! ${error.message}`;

          if(data.getSearchResults.status && 
data.getSearchResults.status !== "260") stopPolling();

          return (
            <div>
              {data.getSearchResults.clusteredOffers.map(offer => (
                  <div key={offer.id} >
                  <div>{offer.id}</div>
                  <div>{offer.bookingId}</div>
                  <div>{offer.totalPrice}</div>
                </div>
              ))}
            </div>
          )
        }}
      </Query>
    )
  }
}

在父组件中,我还需要当前搜索的状态。因此,我已经在我的ApolloClient中添加了一个clientState,以将远程数据写入客户端缓存:

import ApolloClient from "apollo-boost";
import Search from './components/Search';

const client = new ApolloClient({
  uri: "http://localhost:4000/graphql",
  clientState: {
    defaults: {
      currentSearch: {
        __typename: 'CurrentSearch',
        status: "0"
      }
    },
  }
});

....
const GET_CURRENT_SEARCH_STATE = gql`
    {
    currentSearch @client {
      status
    }
  }
`;

您可以看到我正在轮询查询组件中使用onCompleted将当前状态写入本地缓存。

这是否有意义,还是应该从缓存的远程数据中读取状态?如果是这样,我如何获取缓存的远程数据?

谢谢!

0 个答案:

没有答案