useQuery的奇怪问题:未读取查询参数

next.js React.js

小卤蛋

2020-03-23

我有一个将字符串(userToFetch)作为变量传递给参数化查询的组件。该组件如下所示:

// pages/index.jsx

import React from 'react';
import { useQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';

const GET_USERS = gql`
  query users ($limit: Int!, $username: String!) {
    users (limit: $limit, where: { username: $username }) {
      username
      firstName
    }
  }
`;

const Home = () => {
  const userToFetch = 'jonsnow';

  const {
    loading,
    error,
    data,
  } = useQuery(
    GET_USERS,
    {
      variables: { limit: 2, username: userToFetch },
      notifyOnNetworkStatusChange: true,
    },
  );

  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    return <p>Error: {JSON.stringify(error)}</p>;
  }
  return (
    <div>
      <ul>
        {data.users.map(user => {
          return <li>{user.username} {user.firstName}</li>;
        })}
      </ul>
    </div>
  );
};

export default Home;

这就是我配置Apollo客户端的方式:

// /apollo-client.js

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import withApollo from 'next-with-apollo';
import { createHttpLink } from 'apollo-link-http';
import fetch from 'isomorphic-unfetch';

const GRAPHQL_URL = 'https://dev.schandillia.com/graphql';

const link = createHttpLink({
  fetch, // Switches between unfetch & node-fetch for client & server.
  uri: GRAPHQL_URL
});

// Export a HOC from next-with-apollo
// Docs: https://www.npmjs.com/package/next-with-apollo
export default withApollo(
  // You can get headers and ctx (context) from the callback params
  // e.g. ({ headers, ctx, initialState })
  ({ initialState, ctx }) => {
    console.log('initialState', initialState);
    console.log('ctx', ctx);

    return new ApolloClient({
      link: link,
      cache: new InMemoryCache()
        //  rehydrate the cache using the initial data passed from the server:
        .restore(initialState || {})
    })
  }
);

该数据库是以下各项的集合users

"users": [
      {
        "username": "negger",
        "firstName": "Arnold",
        "lastName": "Schwarzenegger"
      },
      {
        "username": "jonsnow",
        "firstName": "Jon",
        "lastName": "Snow"
      },
      {
        "username": "tonystark",
        "firstName": "Tony",
        "lastName": "Stark"
      }
    ]
  }

现在,尽管这应该工作(当我在位于https://dev.schandillia.com/graphql的 graphql操场上运行查询时,它确实可以工作),但代码运行的方式就像该where子句不存在一样!它只是返回所有结果,就像正在运行的查询是:

users {
  _id
  username
  firstName
}

In order to reproduce the issue, visit https://www.schandillia.com. The page ought to display a list with only one element consisting of a matching username-firstName value: jonsnow Jon but it returns two entries, negger Arnold and jonsnow Jon (respecing limit but completely ignoring where). Now, run the same query with jonsnow as a where parameter in https://dev.schandillia.com/graphql:

{
  users(where: { username: "jonsnow" }) {
    _id
    username
    firstName
  }
}

And the results would be exactly as expected:

{
  "data": {
    "users": [
      {
        "_id": "5d9f261678a32159e61018fc",
        "username": "jonsnow",
        "firstName": "Jon",
      }
    ]
  }
}

What am I overlooking?

P.S.: The repo is up for reference at https://github.com/amitschandillia/proost/tree/master/apollo-nextjs.

UPDATE: In order to track down the root cause, I tried logging some values in apollo-client.js:

console.log('initialState', initialState);

Strangely, the output shows the right query, along with the variables being passed, but wrong results:

...
ROOT_QUERY.users({"limit":2,"where":{"username":"jonsnow"}}).0:
  firstName: "Arnold"
  username: "negger"
  __typename: "UsersPermissionsUser"
...

UPDATE: Here's a screenshot of results in my Apollo Client Developer Tools:

在此处输入图片说明

第2854篇《useQuery的奇怪问题:未读取查询参数》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
泡芙LEY 2020.03.23

Strapi生成的模式为where属性提供了一个JSON类型,因此您必须将查询变量中的整个where部分作为JSON传递,因为不会注入变量。

# Write your query or mutation here
query users($where: JSON) {
  users(where: $where) {
    username
    firstName
  }
}

变量看起来像:

{"where": {"username": "jonsnow"}}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android