打字稿阿波罗gql反应将变量传递给功能成分

时间:2020-05-19 02:36:48

标签: reactjs typescript graphql apollo

我正试图以这种功能将变量注入GQL查询中

const ALL_PEOPLE_QUERY = gql`
  query All_People_Query {
    allPeople {
      people {
        id
        name
      }
    }
  }
`;

interface Data {
  allPeople: {
    people: Array<{ id: string; name: string }>;
  };
};

interface Variables {
  first: number;
};

const AllPeopleComponent = <Query<Data, Variables> query={ALL_PEOPLE_QUERY}>
  {({ loading, error, data }) => { ... }}
</Query>

来自here

做这样的事情


export const AllPeopleComponent = () => (<Query<Data, Variables> query={ALL_PEOPLE_QUERY}>
  {({ loading, error, data }) => { ... }}
</Query>
);


ReactDOM.render(<ApolloProvider client={client}><AllPeopleComponent/></ApolloProvider>, document.getElementById('list'));

但是如何在reactDom调用中将变量注入查询中?

1 个答案:

答案 0 :(得分:0)

所以我自己回答

我最终在自己的架构中使用codegen.yml中的codegen

overwrite: true
schema: "<endpoint>"
documents: "src/**/*.graphql"
generates:
  src/generated/schemagql.tsx:
    plugins:
      - "typescript"
      - "typescript-operations"
      - "typescript-react-apollo"
  ./graphql.schema.json:
    plugins:
      - "introspection"

请务必注意,文档是指实际的查询,变异等,而不是架构定义中的任何内容。 因此,对于上述内容,有一个要匹配的文件(已更改为添加变量)

  query All_People_Query( $name: String!) {
    allPeople(name: $name) {
      people {
        id
        name
      }
    }
  }

这将生成您需要的所有类型

和最后一位

const AllPeopleComponent = (props: !!GeneratedVariables!!) => {
  const {data, error ,loading} = useQuery<!!GeneratedQuery!!,!!GeneratedVariables!!>(!!GeneratedDocument!!, { variables: { name: props.name } });
  if (loading)
    return <div>Loading...</div>;
  }

  if (error || !data) {
    return <div>ERROR</div>;
  }

  return !!some html!!
};

ReactDOM.render(<ApolloProvider client={client}><AllPeopleComponent name="value"/></ApolloProvider>, document.getElementById('root'));

这是未经测试的,基于Apollo文档,但请查看我的repo的工作原理