如何从React组件中写入apollo缓存而不丢失“this”的上下文 [英] How to write to apollo cache from within React component with out losing context of "this"

查看:97
本文介绍了如何从React组件中写入apollo缓存而不丢失“this”的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试从 react 组件中读取apollo缓存时遇到问题,该变异工作并写入我的服务器并返回数据但是在传递给我的更新时函数似乎在 inMemoryCache.js

I'm having trouble trying to read from apollo cache from within a react component the mutation works and writes to my server and returns the data but when passed to my update function it seems to lose the context of this when in inMemoryCache.js


  • 时失去了这个的上下文apollo-cache-inmemory:^ 1.2.5

  • react-apollo:^ 2.1.4

  • apollo- boost:^ 0.1.7


TypeError:无法读取undefined $的属性read b $ b at ./node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.readQuery

TypeError: Cannot read property 'read' of undefined at ./node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.readQuery



import React, { Component } from "react";
import { graphql } from "react-apollo";
import trim from "lodash/trim";

import AuthorForm from '../components/author-form';

import ALL_AUTHORS from "../graphql/getPosts.query";
import CREATE_AUTHOR from "../graphql/createAuthor.mutation";

class CreateAuthor extends Component {
  state = {
    errors: false
  };

  onSubmit(event) {
    event.preventDefault();

    const form = new FormData(event.target);

    const data = {
      firstName: form.get("firstName"),
      lastName: form.get("lastName")
    };

    if (!data.firstName || !data.lastName) {
      return this.setState({ errors: true });
    }

    this.create({
      firstName: trim(data.firstName),
      lastName: trim(data.lastName)
    });
  }

  async create(variables) {
    const { createAuthor } = this.props;
    this.setState({ errors: false });

    try {
      await createAuthor({
        variables,
        update: (cache, data) => this.updateCache(cache, data)
      })
    } catch (e) {
      this.setState({ errors: true })
    }
  }

  updateCache({ readQuery, writeQuery }, { data: { createAuthor }, errors }) {
    if (errors) {
      return;
    }
    const { allAuthors } = readQuery({
      query: ALL_AUTHORS,
      defaults: {
        allAuthors: []
      }
    });
    /*eslint-disable*/ console.log(allAuthors);
  }

  render() {
    return (
      <div>
        <AuthorForm onSubmit={this.onSubmit.bind(this)}/>
        <OnError/>
      </div>
    );
  }
}

export default graphql(CREATE_AUTHOR, { name: "createAuthor" })(CreateAuthor);

是否与我绑定到onSubmit按钮?如果是这样,将一个函数附加到一个元素而不丢失组件中的上下文并且仍然允许apollo缓存正常运行的正确方法是什么。

is it to do with me binding this to the onSubmit button? if so what is the proper way to attach a function to a element without losing context of this within the component and still allow apollo cache to function properly.

推荐答案

我正在失去这种情况,因为我正在解构第一个论点。这就是我最终解决的问题。

I was losing the context of this because I was deconstructing the first argument. this is what I settled on in the end.

当ROOT_QUERY对象上没有allAuthors时,它会抛出错误,因此将其添加到我的return语句中。

It throw errors when there were no allAuthors on the ROOT_QUERY object so added it to my return statement.

这不是一种更新缓存的理想方式,不应该将默认参数传递给readQuery,以防止抛出错误。

this doesn't feel like an ideal way of updating the cache shouldn't default param passed to readQuery prevent the error thrown.

 updateCache(cache, { data: { createAuthor }, errors }) {
    if (errors || !cache.data.data.ROOT_QUERY.allAuthors) {
      return;
    }

    const query = ALL_AUTHORS;

    const { allAuthors } = cache.readQuery({
      query,
      defaults: {
        allAuthors: []
      }
    });

    const data = {
      allAuthors: allAuthors.concat([createAuthor])
    };

    cache.writeQuery({
      query,
      data
    });
  }

这篇关于如何从React组件中写入apollo缓存而不丢失“this”的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆