从外部使用Apollo GraphQL refetch方法

时间:2019-02-13 08:49:00

标签: javascript reactjs react-apollo

我的渲染功能

translateFileAndRefetchQuery = (urn) => {
    translateFile(urn);
    // How do I refetch data from here?
  };

render() {
    const translateFormatter = (cell, row) => {
      return (
        <span>
          <Button
            onClick={() => translateFileAndRefetchQuery(row.urn)}
          >
            Translate
          </Button>
        </span>
      );
    };

    const columns = [
      {
        dataField: 'name',
        text: 'Name',
      },
      {
        dataField: 'lastUpdated',
        text: 'Last updated',
      },
      {
        dataField: 'lastTranslated',
        text: 'Translate',
        formatter: translateFormatter,
      },
    ];

    return (
      <>
        <h3>Models</h3>
        <h4>Root > Plans</h4>

        {this.state.plansFolderUrn != null &&
        <Query query={getProjects()}>
          {(data, refetch) => (
            <>
              <BootstrapTable
                keyField="name"
                data={data.projects}
                columns={columns}
              />
            </>
          )}
        </Query>
        }
      </>
    );
  }

我正在使用具有refetch方法的阿波罗数据提取器。我需要从Query外部调用它。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以在不同的回调中传递该函数。我在translateFormatter上添加了一个装饰器,以使其无法立即调用:

translateFileAndRefetchQuery = (urn, refetch) => {
    translateFile(urn);
    refetch();
};

render() {
    const translateFormatter = refetch => (cell, row) => {
        return (
            <span>
                <Button
                    onClick={() => translateFileAndRefetchQuery(row.urn, refetch)}
                >
                    Translate
        </Button>
            </span>
        );
    };

    const getColumns = refetch => [
        {
            dataField: 'name',
            text: 'Name',
        },
        {
            dataField: 'lastUpdated',
            text: 'Last updated',
        },
        {
            dataField: 'lastTranslated',
            text: 'Translate',
            formatter: translateFormatter(refetch),
        },
    ];

    return (
        <>
            <h3>Models</h3>
            <h4>Root > Plans</h4>

            {this.state.plansFolderUrn != null &&
                <Query query={getProjects()}>
                    {(data, refetch) => (
                        <>
                            <BootstrapTable
                                keyField="name"
                                data={data.projects}
                                columns={getColumns(refetch)}
                            />
                        </>
                    )}
                </Query>
            }
        </>
    );
}