我们可以使用 Query 和 Mutation 向服务器发出一些请求。在这些查询中,我们可以传递一些参数,并且在这两种情况下我们都会从服务器获得一些结果。唯一的必要区别是我们可以像“this.props.mutation”一样从我们的道具中调用变异,但它看起来像是一种语法糖,因为我们可以将我们的 HOC 包装在“withApollo”中,我们将收到“query”道具中的方法也是如此。那么这两种类型的请求之间的主要区别是什么?
我有一个名为deleteSong. 我想知道在突变通过后如何将多个查询传递到refetchQueries?
this.props
.deleteSong({
variables: { id },
refetchQueries: [{ query: fetchSongs }] //<-- I only know how to pass 1 query
})
.then(() => {})
.catch(err => {
this.setState({ err });
});
Run Code Online (Sandbox Code Playgroud) 这就是我试图在我的本机应用程序中实现 apollo graphQL 的方式。
但是我确实得到了错误
Could not find "client" in the context of Query or as passed props. Wrap the root component in an <ApolloProvider>
Run Code Online (Sandbox Code Playgroud)
所以我认为我已经做到了这一点,但显然我误解了一些东西。
import React, { Component } from 'react'
import { ApolloProvider, graphql } from 'react-apollo'
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import gql from 'graphql-tag'
import Routes from './config/routes'
// Initialize the Apollo Client
const client = new ApolloClient({
link: createHttpLink({ uri: 'http://localhost:3000' …Run Code Online (Sandbox Code Playgroud) 我正在使用 Apollo Client 并且正在学习 Typescript。我有一个Mutation带有此更新道具的组件:
(cache, { data: { createTask } }) => {
const allTasks = cache.readQuery({ query: ALL_TASKS }).allTasks;
}
Run Code Online (Sandbox Code Playgroud)
我收到两个编译错误:
Object is possibly 'null'.
Property 'allTasks' does not exist on type '{}'.
Run Code Online (Sandbox Code Playgroud)
我理解总体思路。readQuery可能会返回null(这是自我混淆,因为文档让我相信当没有找到结果时会抛出错误(https://www.apollographql.com/docs/react/advanced/caching.html#readquery)。
我怎样才能让编译器让我allTasks从结果中读取属性readQuery?
另外,仅供参考,我尝试运行console.log(cache.readQuery({ query: ALL_TASKS }))并确认那里确实存在有效数据并调用了一个属性。
我正在尝试使用s 中的useMutation钩子react-apollo-hook来执行删除突变,但是在以下代码中我很难将帖子的 ID 值传递给突变钩子:
const Posts = () => {
const { data, error, loading } = useQuery(GET_POST)
const onDeleteHandler = useMutation(DELETE_POST, {
variables: { id }
})
if (loading) return <div>...loading</div>
if (error) return <div>Error</div>
return data.posts.map(({id, title, body, location, published, author}) => {
return (
<div className="card" key={id}>
<p>id: {id}</p>
<p>title: {title}</p>
<p>body: {body}</p>
<p>location: {location}</p>
<p>published: {published}</p>
<p>author: {author.name}</p>
<Link to={`/post/${id}/edit`}>
Edit
</Link>
<button
onClick={onDeleteHandler}>
Delete
</button>
</div>
)
})
}
Run Code Online (Sandbox Code Playgroud)
由于钩子不能用作回调函数,因此我不能useMutation …
我有 useQuery 和 useMutation 从 react-apollo-hooks 背靠背。我希望能够使用 useQuery 的返回值作为 useMutation 的变量。目前, useQuery 的值没有及时返回变量,导致变量未定义。
const { data, error, loading } = useQuery(GET_POSTS, {
variables: {
id: props.match.params.id
}
})
const item = props.match.params.id
const owner = data.posts[0].author.id
const variables = { item , owner, startDate, endDate }
const bookItem = useMutation(CREATE_BOOKING_MUTATION, variables)
Run Code Online (Sandbox Code Playgroud)
变量data.posts[0].author.id显示未定义。如何确保及时定义返回值?
在我的 hasura.io 数据库中,我有一个booking表,我在其中存储具有以下属性的预订:
现在,从 UI 中,当用户进行预订时,我想检查之前是否有任何涉及这些日期范围的预订。
例如。用户想要在以下日期进行预订:
{
"from": "2020-03-31T14:00:00+00:00",
"to": "2020-03-31T17:00:00+00:00"
}
Run Code Online (Sandbox Code Playgroud)
但在同一天有一个预订:
{
"from": "2020-03-31T15:00:00+00:00",
"to": "2020-04-01T17:00:00+00:00"
}
Run Code Online (Sandbox Code Playgroud)
请注意,此预订不是在用户尝试预订的日期范围内进行的。因此,以下查询将不返回任何内容。
query CheckBooking($from: timestamptz!, $to: timestamptz!) {
booking(where: {_and: [{from: {_lte: $from}}, {to: {_gte: $to}}]}) {
id
from
to
}
}
Run Code Online (Sandbox Code Playgroud)
以上是我尝试过但没有成功的方法。任何人都可以帮助找出检查范围内或用户新预订内是否有任何预订的正确查询是什么?
我正在使用 React Apollo 从我的服务器获取数据。当我的页面加载时,我使用 useQuery 来检索数据。这工作正常。问题是当我对搜索表单进行更改时,这会更新状态,导致不需要的重新渲染,从而再次调用服务器。
我只想在页面加载和单击搜索按钮时调用服务器。
使用查询:
const { loading: loadingLessons, error: lessonsError, data: lessons } = useQuery(
LESSON_BY_PARAMS,
{
variables: { findLessonsInput: searchParams },
},
);
Run Code Online (Sandbox Code Playgroud)
当我更改表单字段时,它会调用 updateFormField 更新 redux 状态,从而导致重新渲染
<Autocomplete
options={categories}
getOptionLabel={(option: any) => option.label}
inputValue={form.category}
defaultValue={() => {
const value = categories.find(option => option.label === form.category);
return value;
}}
onChange={(event, value) => updateFormField('category', value?.label)}
renderInput={params => (
<TextField {...params} label="Category" variant="outlined" fullWidth />
)}
/>
Run Code Online (Sandbox Code Playgroud)
我正在使用反应钩子。
我目前正在尝试使用 Mocked Provider 测试样式组件,如下所示:
import React from "react";
import TestResults from "./TestResults";
import {
render,
cleanup,
findByTestId,
findByText,
waitForElement,
} from "@testing-library/react";
import { MockedProvider } from "@apollo/react-testing";
describe("TestResultsComponent", () => {
describe("Overall", () => {
it("should render successfully - base", async () => {
const { getByText } = render(
<MockedProvider>
<TestResults />
</MockedProvider>
);
expect(getByText("Preview")).toBeInTheDocument();
});
});
});
Run Code Online (Sandbox Code Playgroud)
我在 TestResults 文件中使用 makeStyles 钩子
当我运行我的测试时,我收到以下错误:
TypeError: theme.spacing is not a function
Material-UI: the `styles` argument provided is invalid.
You …Run Code Online (Sandbox Code Playgroud) unit-testing reactjs react-apollo apollo-client react-testing-library
我正在尝试让useQuery钩子与 TypeScript 一起工作。
这是我的查询
export const FETCH_LINKS = gql`
query FetchLinks {
feed {
links {
id
createdAt
url
description
}
}
}
`;
Run Code Online (Sandbox Code Playgroud)
我从 GraphQL 模式生成了类型 graphql-codegen
export type Feed = {
__typename?: 'Feed';
links: Array<Link>;
count: Scalars['Int'];
};
export type Link = {
__typename?: 'Link';
id: Scalars['ID'];
createdAt: Scalars['DateTime'];
description: Scalars['String'];
url: Scalars['String'];
postedBy?: Maybe<User>;
votes: Array<Vote>;
};
Run Code Online (Sandbox Code Playgroud)
在我的组件中,我将类型应用于useQueryhook
const { data, loading, error } = useQuery<Feed>(FETCH_LINKS);
Run Code Online (Sandbox Code Playgroud)
问题是在data变量中我收到了以下形状的对象:
{
feed: {
__typename …Run Code Online (Sandbox Code Playgroud) react-apollo ×10
reactjs ×7
graphql ×5
apollo ×2
javascript ×2
react-hooks ×2
typescript ×2
apollostack ×1
gql ×1
hasura ×1
react-native ×1
react-redux ×1
unit-testing ×1