首页 > 解决方案 > react-apollo 突变不会重新获取

问题描述

我有一个组件RecipeList和另一个AddRecipe 。添加食谱后,它应该被重定向到 RecipeList 并显示所有项目。这是 AddRecipe 组件的代码。

import React ,{Component}from 'react'
import { Mutation } from "react-apollo";
import {ADD_RECIPE} from '../../mutations';
import Error from '../Error';
import {withRouter} from 'react-router-dom';
import {GET_ALL_RECIPIES} from '../../queries'

class AddRecipe extends Component {
  ...
  onSubmit(event,addRecipe){
    event.preventDefault();
    addRecipe().then(
      ({data})=>
        {
          this.props.history.push("/")
        }
      )
  }
  render (){
    const{name,category,description,instruction,username} = this.state;
    return(<div className="App">
      <h2>Add recipe</h2>
      <Mutation
             mutation={ADD_RECIPE} 
             variables={{name,category,description,instruction,username}} 
             update={(cache, {data:{addRecipe}}) => {
                  const {getAllRecipes} = cache.readQuery({ query: GET_ALL_RECIPIES });
                  cache.writeQuery({
                    query:GET_ALL_RECIPIES,
                    data:{getAllRecipes:getAllRecipes.concat[addRecipe]}
                  })
              }} >
      {(addRecipe, {data,loading,error})=>

           (<form className="form" onSubmit={event=>this.onSubmit(event,addRecipe)}>
                  <input type="text" name="name" onChange={this.handleChange.bind(this)} placeholder="recipe name" value={name}/>
                  <select name="category" value="breakfast" id="" onChange={this.handleChange.bind(this)} value={category}>
                    <option value="breakfast">breakfast</option>
                    <option value="lunch">lunch</option>
                    <option value="dinner">dinner</option>
                    <option value="snack">snack</option>
                  </select>
                  <input type="text" name="description" onChange={this.handleChange.bind(this)} placeholder="recipe description" value={description}/>
                  <textarea name="instruction" id="instruction" cols="30" rows="10" onChange={this.handleChange.bind(this)} value={instruction}> </textarea>
                  <button type="submit" className="button-primary" disabled = {loading || this.validateForm()}>submit</button>
                  {error && <Error error={error}/>}
            </form>)

      }
      </Mutation>
    </div>)
  }

我的添加配方突变是:

import gql from 'graphql-tag';


//RECIPE QUERY
export const GET_ALL_RECIPIES =gql`
query {
    getAllRecipes{
        name
        _id
        category

    }
}
`

最后得到配方列表查询是:

import gql  from "graphql-tag";

export const GET_RECIPE_ITEM =gql`
query($id:ID!){
        getRecipeItem(_id:$id){

          _id
          name
          category
          description
          instruction
          createdDate
          likes
          username
        }
}`

提交表单并添加食谱后,我希望 第一个组件被重定向到食谱列表, 第二个组件的食谱列表包括新添加的食谱。 但我看到旧列表不包含任何新添加的食谱,并且为了显示新组件,我应该刷新页面

标签: graphqlapolloreact-apolloapollo-clientmutation

解决方案


Apollo Client 缓存数据以提高性能,它不会重新获取您的食谱列表,因为它已经在缓存中。

为了克服这个问题,您可以fetchPolicy从默认更改cache-firstcache-and-networknetwork-only但我不建议在您的情况下这样做,或者在突变getAllRecipes后重新获取查询,如下所示:addRecipe

<Mutation
 mutation={ADD_RECIPE} 
 variables={{name,category,description,instruction,username}}
 refetchQueries=['getAllRecipes']
>
 ...
</Mutation>

推荐阅读