我正在使用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));
答案 0 :(得分:1)
您可以使用reducer
和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
的更多信息