【问题标题】:how to update a query props.data after a query onClick如何在查询 onClick 后更新查询 props.data
【发布时间】:2017-05-07 06:21:38
【问题描述】:

我正在使用 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));

【问题讨论】:

  • 请发布您尝试过的内容以及当前尝试的无效内容
  • 我添加了我正在尝试使用的代码示例

标签: reactjs graphql apollo apollostack react-apollo


【解决方案1】:

您可以在 query1 中添加 reducertype==='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

【讨论】:

  • 非常感谢,这很好用,我用第二个查询尝试了reducer,所以它不起作用。
猜你喜欢
  • 2013-06-12
  • 2021-11-12
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
  • 2019-09-06
  • 2011-07-23
相关资源
最近更新 更多