启用缓存后,Apollo客户端,React,事件

时间:2018-10-25 14:04:52

标签: reactjs react-apollo apollo-client

const sidebar = ({ selectedSidebarItem, selectItemCb }) => {
      const doExcelExport = () => {
        const data = client.readQuery({ query: getLeveransprojektOrders });
        const rows = data.projectOrders.map(order => Object.keys(order).map(key => order[key]));
        ....
      };

      return (
        <div className="sidebar">
          <button disabled={some condition}>Export excel</button> 
        </div>
      );
    };

我需要禁用一个按钮,直到Apollo缓存中有项目为止。有内置的方法吗?在文档中找不到有关此内容的任何信息。

1 个答案:

答案 0 :(得分:0)

您可以通过如下所示的render prop函数访问Query的loading prop:

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

const GET_DOGS = gql`
  {
    dogs {
      id
      breed
    }
  }
`;

const Dogs = ({ onDogSelected }) => (
  <Query query={GET_DOGS}>
    {({ loading, error, data }) => {
      if (loading) return "Loading...";
      if (error) return `Error! ${error.message}`;

      return (
        <select name="dog" onChange={onDogSelected}>
          {data.dogs.map(dog => (
            <option key={dog.id} value={dog.breed}>
              {dog.breed}
            </option>
          ))}
        </select>
      );
    }}
  </Query>
);

Check docs了解更多详情。

或者您可以使用HOC将此道具传递给组件。

import { graphql } from 'react-apollo'

const Dogs = ({ loading, dogs }) => <div>{loading && "Loading..."}</div>

const withDogs = graphql(GET_DOGS, {
  props: ({ data: { loading, error, dogs } }) => ({
    loading,
    error,
    dogs
  })
})

export default withDogs(Dogs)

请注意,您可能不需要像以前那样直接在事件处理程序中加载数据。