如何在不丢失“ this”上下文的情况下从React组件内写入阿波罗缓存

时间:2018-06-28 11:18:51

标签: javascript reactjs graphql apollo apollo-client

我在尝试从react组件中读取阿波罗缓存时遇到麻烦,该突变有效并写入我的服务器并返回数据,但是当传递给我的更新函数时,它似乎失去了上下文在inMemoryCache.js

  • “ apollo缓存内存”:“ ^ 1.2.5”
  • “反应阿波罗”:“ ^ 2.1.4”
  • “阿波罗升压”:“ ^ 0.1.7”
  

TypeError:无法读取未定义的属性“ read”       在./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缓存正常运行。

1 个答案:

答案 0 :(得分:0)

因为我正在解构第一个论点,所以我失去了它的上下文。这就是我最后要解决的问题。

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

这似乎不是更新缓存的理想方法,不应通过将默认参数传递给readQuery来防止引发错误。

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