当用户将文本键入输入文本字段时
我正在尝试使用GraphQl和React构建一种自动完成搜索栏。 我的问题是:如何设法触发一个函数,即一旦检查输入的长度大于3个字符 - 将一个挂钩从Apollo客户端库(USEQUERY或USELAZYQUERY)调用。认为无法在功能或条件中触发使用量,我读到为此目的是解决方案,但是我没有找到任何情况清楚地暴露出来的示例。
我正在使用的这种方法...
我已经设置了此功能:
const FetchProducts = (input) => {
const [getProducts,{ data, loading, error }] = useLazyQuery(GET_PRODUCTS_QUERY, {
variables: {input}
})
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return products.results.map(({ id, name }) => (
<div key={id}>
<p>
{name}
</p>
</div>
));
};
我的get_produtcs_query看起来像这样,
const GET_PRODUTCS_QUERY = gql`
query getProducts ($name: String!){
products( page: 1, filter: { name: $name }) {
results {
name,
id
}
}
}
`;
我想触发fetchproducts方法当我的输入文本字段的Te值将具有3个以上的字符时。 类似的东西:
const triggerFetch = () => {
input.length > 3 ? FetchProducts(input) : '';
};
这是我在函数组件上返回的JSX的
<input type="text" onChange={e => setInput(e.target.value), triggerFetch } value={input} placeholder="Search..."/>
块
I'm trying to build a sort of autocomplete searchbar using GraphQL and React.
My question is: how can I manage to trigger a function that -once it checks the length of the input is bigger than 3 characters- calls one the hooks from the apollo client library (useQuery or useLazyQuery). Think that useQuery cannot be triggered inside a function or condition, I've read that for this purpose useLazyQuery can be a solution, but I do not have found any example where this situation was clearly expose.
This kind of approach I'm working on...
I have set up this function:
const FetchProducts = (input) => {
const [getProducts,{ data, loading, error }] = useLazyQuery(GET_PRODUCTS_QUERY, {
variables: {input}
})
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return products.results.map(({ id, name }) => (
<div key={id}>
<p>
{name}
</p>
</div>
));
};
My GET_PRODUTCS_QUERY look like this
const GET_PRODUTCS_QUERY = gql`
query getProducts ($name: String!){
products( page: 1, filter: { name: $name }) {
results {
name,
id
}
}
}
`;
I would like to trigger FetchProducts method when te value of my input text field will have more than 3 characters.
Something like this:
const triggerFetch = () => {
input.length > 3 ? FetchProducts(input) : '';
};
This is a chunk from the JSX that I return on the my function component:
<input type="text" onChange={e => setInput(e.target.value), triggerFetch } value={input} placeholder="Search..."/>
I do not see where or how can I call the getProducts() function setup on the useLazyQuery hook
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要此代码的懒惰。您可以用懒惰实现它,但是您必须重新编写代码。
You don't need a LazyQuery with this code. You can implement it with a LazyQuery but you'll have to rework your code.