【问题标题】:Urql useQuery - How to clear data on query / variables changes?Urql useQuery - 如何清除查询/变量更改的数据?
【发布时间】:2021-11-21 10:33:33
【问题描述】:

如何配置挂钩,使其在从网络或缓存中获取新数据时不会返回上一个查询中的数据?
类似于参数keepPreviousData: false。

如果您动态更改 useQuery() 挂钩的变量或查询,则结果仍将包含以前的数据,同时获取新数据。 虽然它对于无限滚动模式非常有用,但对于像搜索界面那样动态变化的查询则较少。在这样的界面中,用户不希望看到与他的搜索查询不再匹配的弃用结果。

示例:

const [search, setSearch] = useState('');

// The hook will fetch data matching the search variable typed by the user
const [result] = useQuery({
  query: "...",
  variables: {search}
});

// If the search variable changes,
// result still contains data from last query
// ???????? while fetching new search
const data = result.data;


return (
  // user types and changes the search variable
  <TextInput onChangeText={setSearch} />
);

PS:如果该功能不存在,我也会奖励那些为此类功能进行 PR 的人。

【问题讨论】:

    标签: reactjs urql


    【解决方案1】:

    根据the documentation for useQuery,

    结果是一个形状为OperationResult 的对象,并添加了fetching: boolean 属性,指示是否正在获取查询。

    因此,检查result.fetching 是否为真就足够了:

    function SearchForm() {
        const [search, setSearch] = useState('');
    
        // The hook will fetch data matching the search variable typed by the user
        const [result] = useQuery({
            query: "...",
            variables: { search }
        });
    
        const data = result.data;
    
        return <>
            <TextInput onChangeText={setSearch} />
            {
                !result.fetching && result.data
                ? <SearchResults data={result.data} />
                : null
            }
        </>;
    }
    

    【讨论】:

    • 我需要选择是否保留数据。有时我想像无限列表一样保留数据,我只需更改一个偏移变量。
    • @Yairopro 那么……选择?问题出在哪里?
    猜你喜欢
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2022-01-21
    • 2021-07-09
    • 2021-08-08
    相关资源
    最近更新 更多