【问题标题】:When to set the initial value of the form?什么时候设置表单的初始值?
【发布时间】:2022-01-20 03:44:57
【问题描述】:

我有这些代码,如果用户第一次打开表单对话框,效果很好。

function PostFormDialog({ id }) {
  const queryClient = useQueryClient()
  const post = useQuery(['post', id], () => fetchPost(id))
  const update = useMutation(() => updatePost(formValue), {
    onSuccess: () => {
      queryClient.invalidateQueries(['post', id])
    },
  })
  if (post.isLoading) {
    return 'loading...'
  }
  return (
    <Dialog {...dialogProps}>
      <Form initialValue={post} onSubmit={update.mutate} />
    </Dialog>
  )
}

但是当我提交一次表单时,我很快再次打开对话框,它会显示最后的数据。此时正在检索数据,但 isLoading 为 false。

我想要:

  • 打开表单对话框后,如果数据过期,等待数据加载完毕,显示loading...
  • 如果你正在编辑表单,切换标签可能会导致数据被检索,但loading...此时不显示

这对我来说很难。我可以通过使用乐观更新来避免它,但是有更好的方法吗?

【问题讨论】:

    标签: react-query


    【解决方案1】:

    尝试使用 react 查询选项。例如:

    useQuery(
      ["post", id],
      () => fetchPost(id),
      { refetchOnMount: true }
    );
    

    【讨论】:

    • 这个也有同样的问题,因为isLoadingfalse,所以打开对话框的时候initialValue的值是stale post data
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2016-12-10
    相关资源
    最近更新 更多