0

在 freecodecamp 上做夜生活应用https://learn.freecodecamp.org/coding-interview-prep/take-home-projects/build-a-nightlife-coordination-app/

我正在尝试实现“Go”按钮,类似 Youtube 或 Instagram 上的“Like”按钮。用户点击按钮数字(统计多少用户去)增加表示用户会去那里,再次点击,它撤销,数字减少,用户不会去那里。

除了问题之外,它似乎运行良好,我必须刷新页面然后,数字增加或减少并引发如下错误:

Invariant Violation: Can't find field getBars({}) on object {
  "getBars({\"location\":\"vancouver\"})": [
    {
      "type": "id",
      "generated": false,
      "id": "Bar:uNgTjA9ADe_6LWby20Af8g",
      "typename": "Bar"
    },
    {
      "type": "id",
      "generated": false,
      "id": "Bar:CwL5jwXhImT_7K5IB7mOvA",
      "typename": "Bar"
    },
    {
      "type": "id",
      "generated": false,
      "id": "Bar:mdt1tLbkZcOS2CsEbVF9Xg",
      "typename": "Bar"
    },
                     .
                     .
                     .

我假设处理更新功能将解决此问题,但与 Apollo 文档中的示例不同:

// GET_TODOS is not dynamic query
// nothing to pass as variables to fetch TODO list

<Mutation
      mutation={ADD_TODO}
      update={(cache, { data: { addTodo } }) => {
        const { todos } = cache.readQuery({ query: GET_TODOS });
        cache.writeQuery({
          query: GET_TODOS,
          data: { todos: todos.concat([addTodo]) },
        });
      }}
    >

我的查询是动态的:

// I have to pass location variable, otherwise it won't fetch anything.

const GET_BARS_QUERY = gql`
  query getBars($location: String!) {
    getBars(location: $location) {
      id
      name
      url
      rating
      price
      image_url
      goings {
        username
      }
      goingCount
    }
  }
`;

我相信我可能需要处理使用 readQuery 和 writeQury 提供位置,但不太确定我应该做什么。

这是我的代码:

const GoButton = ({ user, bar }) => {
  const { token } = user;
  const { id, goings, goingCount } = bar;

  const [userGoes] = useMutation(GO_MUTATION, {
    variables: { yelp_id: id },
    update(proxy, result) {
      const data = proxy.readQuery({
        query: GET_BARS_QUERY
      });
      data.getBars = [result.userGoes, ...data.getBars];
      proxy.writeQuery({ query: GET_BARS_QUERY, data });
    }
  });

    return (
    <Button onClick={userGoes}>
      Go {goingCount}
    </Button>
  );
};

const GO_MUTATION = gql`
  mutation go($yelp_id: String!) {
    go(yelp_id: $yelp_id) {
      id
      goings {
        id
        username
      }
      goingCount
    }
  }
`;

export default GoButton;

完整代码在这里https://github.com/footlessbird/Nightlife-Coordination-App

4

1 回答 1

1

当您读/写 getBars 查询时,您需要将位置作为变量传递

  const [userGoes] = useMutation(GO_MUTATION, {
variables: { yelp_id: id },
update(proxy, result) {
  const data = proxy.readQuery({
    query: GET_BARS_QUERY,
    variables: {
        location: 'New York'
    }
  });
  data.getBars = [result.userGoes, ...data.getBars];
  proxy.writeQuery({ query: GET_BARS_QUERY, data,
    variables: {
        location: 'New York'
    }
   });
}
});
于 2019-10-24T02:29:04.730 回答