2

我正在使用 Apollo 执行 2 个查询,
第一个查询由 Apollo 自动执行,
第二个查询在单击按钮时执行,并且此查询的结果应该更新第一个查询的一部分(就像updateQueries突变一样)。

这是我试过的代码:

import React from 'react';
import {graphql, withApollo} from 'react-apollo';
import gql from 'graphql-tag';

class MaPage extends React.Component {

  loadAllResults = ()=> {
        return this.props.client.query({
            query: query2,
            variables: {userId: 'user_id_1'}
            //I want to update the results of query1 by the results of query2
        });
    }

  render() {
        if (this.props.data.loading) {
            return (
                <div>Loading... </div>
            );
        }
        else {
            return (
                <div>
                    {this.props.data.user.allResults.map((result)=> {
                        return (<span >{result.score} | </span>)
                    })
                    }
                    <button onClick={this.loadAllResults}>load all results</button>
                </div>
            );
        }
    }
}

const query1 = gql`
    query GetInfos ($userId:ID!)){
        user(id:$userId){
            id
            name
            allResults(first:2){
                id
                score
            }
            #get other attributes
        }
    }
`;
const query2 = gql`
    query getAllResults ($userId:ID!){
        allResults(userId:$userId){
            id
            score
        }
    }
`;

export default  withApollo(
    graphql(query1,
        {
            options: (ownProps) => {
                return {
                    variables: {userId: 'user_id_1'}
                };
            }
        }
    )
    (MaPage));
4

1 回答 1

1

您可以reducerquery1中添加一个type==='APOLLO_QUERY_RESULT'operationName==='getAllResults'

例子:

graphql(query1,
  {
    options: (ownProps) => {
     return {
       variables: {userId: 'user_id_1'},
       reducer: (previousResult, action) => {
                 if (action.type === 'APOLLO_QUERY_RESULT' && action.operationName === 'getAllResults'){
                    return update(previousResult, {
                       user: { ... }
                    })
                 }
                return previousResult;
              }
            };
        }
    }
)

更多信息请访问http://dev.apollodata.com/react/cache-updates.html#resultReducers

于 2016-12-22T12:56:36.263 回答