how to update a query props.data after a query onClick

1.8k views Asked by At

I'm using Apollo to execute 2 queries,
the first query is executed automatically by Apollo,
the second query is executed when a button is clicked, and the results of this query should update a part of the first query (just like updateQueries does for mutations).

This is the code I tried:

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));
1

There are 1 answers

1
djedi On BEST ANSWER

You might add a reducer in query1 with type==='APOLLO_QUERY_RESULT' and operationName==='getAllResults'

Example:

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;
              }
            };
        }
    }
)

More infos at http://dev.apollodata.com/react/cache-updates.html#resultReducers