首页 > 解决方案 > 如何从另一个组件重新获取 graphql 查询?

问题描述

我对 React 非常陌生,尤其是对 graphql。

每次使用突变 createEvent 时,我都会尝试重新获取事件查询,因此包含所有事件的页面将自动更新,不需要刷新。

但是,我找不到连接这两个查询的方法。

我的突变 createEvent 来自“form.jsx”文件:

  const body = {
    query:
      "mutation{" +
      "createEvent(eventInput:{num1:" +
      '"' +
      this.state.num1.toString() +
      '"' +
      ",num2:" +
      '"' +
      this.state.num2.toString() +
      '"' +
      "}){" +
      "_id " +
      "num1 " +
      "num2 " +
      "addition " +
      "multiply" +
      "}}"
  };
  fetch("https://localhost:8000/graphql", {
    method: "POST",
    body: JSON.stringify(body),
    headers: {
      "Content-Type": "application/json"
    }
  })
    .then(res => {
      if (res.status !== 200 && res.status !== 201) {
        throw new Error("Failed!");
      }
      return res.json();
    })
    .then(resData => {
      console.log(resData);
    })
    .catch(err => {
      console.log(err);
    });

这是我从“myTable.jsx”文件中查询的事件:

const body = {
  query:
    "query {" +
    "events {" +
    "_id " +
    "num1 " +
    "num2 " +
    "addition " +
    "multiply" +
    "}}"
};
//console.log(body);
fetch("https://localhost:8000/graphql", {
  method: "POST",
  body: JSON.stringify(body),
  headers: {
    "Content-Type": "application/json"
  }
})
  .then(res => {
    if (res.status !== 200 && res.status !== 201) {
      throw new Error("Failed!");
    }
    return res.json();
  })
  .then(resData => {
    const events = resData.data.events;
    this.setState({ list: events });
  })
  .catch(err => {
    console.log(err);
  });

我在 Promise 'then' 函数中尝试了 refetchQueries 函数,但它崩溃了。

标签: reactjsgraphqlapolloreact-apollo

解决方案


我从 queries.js 文件中导出了查询,然后启用了使用 ApolloClient 的重新获取选项。


推荐阅读