📅  最后修改于: 2023-12-03 15:35:32.419000             🧑  作者: Mango
In React applications, when using uselazyquery
to fetch data from a GraphQL endpoint, the refetch
method can be used to fetch new data whenever it is needed. However, if you want to refetch data from a child component, you need to pass the refetch
method down as a prop.
This can become cumbersome if the component tree is deep, and it can be hard to manage the passing of the refetch
method through multiple layers of components.
Fortunately, useLazyQuery
provides us with an easy way to solve this problem. Instead of passing the refetch
method down through the component tree, we can simply pass the refetch
function to the child component as a prop. This way, the child component can call the refetch
function whenever it needs to fetch fresh data.
Here's an example of how to do this:
import { useLazyQuery } from '@apollo/client';
import { gql } from 'graphql-tag';
function ParentComponent() {
const [getUsers, { loading, error, data }] = useLazyQuery(gql`
query getUsers($limit: Int) {
users(limit: $limit) {
id
name
email
}
}
`);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<div>
<ChildComponent refetch={getUsers} />
<ul>
{data.users.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
</div>
);
}
function ChildComponent({ refetch }) {
function handleClick() {
refetch({ variables: { limit: 10 } });
}
return <button onClick={handleClick}>Refetch Users</button>;
}
In the example above, the getUsers
function returned by useLazyQuery
is passed down to the ChildComponent
as a prop called refetch
. In the ChildComponent
, refetch
is used as the callback function for a button's onClick
event handler. When the button is clicked, the refetch
function is called with updated variables to fetch fresh data, which is then updated in the ParentComponent
's render method.
By doing this, we avoid the need to pass the refetch
method multiple levels deep through the component tree, making our code cleaner and more manageable.