Such a problem. i need to skip the request when there is no user.
i tried doing this and that
这真是个问题。当没有用户时,我需要跳过该请求。我试着做这个做那个
const { data: carts = [] as ICart[], isFetching } =
api.useGetCartProductsQuery(user.id, { skip: !user})
const { data: carts = [] as ICart[], isFetching } =
api.useGetCartProductsQuery(user.id, { skip: true })
but every time I get an error
但每次我出错
Unhandled Runtime Error TypeError: Cannot read properties of null (reading 'id')
Source
src\app\dashboard\Dashboard.tsx (35:35) @ id
33 |
34 | const { isLoading, data: carts = [] as ICart[] } =
> 35 | api.useGetCartProductsQuery(user.id, { skip: true })
Tell me how to make it work correctly.
告诉我怎么才能让它正常工作。
I tried doing this and that
我试着做这个做那个
const { data: carts = [] as ICart[], isFetching } =
api.useGetCartProductsQuery(user.id, { skip: !user})
const { data: carts = [] as ICart[], isFetching } =
api.useGetCartProductsQuery(user.id, { skip: true })
更多回答
优秀答案推荐
You are on the same time still trying to access user.id
- this is JavaScript code that is executed outside of RTK Query, which you have written:
同时,您仍在尝试访问user.id-这是在RTK查询之外执行的JavaScript代码,您已经编写了:
api.useGetCartProductsQuery(user.id, { skip: !user })
You could try to get around that by providing some kind or default:
您可以尝试通过提供某种类型或默认设置来绕过这一点:
api.useGetCartProductsQuery(user ? user.id : undefined, { skip: !user })
but that is kinda unsatisfying to read.
但这读起来有点令人不满意。
Instead you can use the skipToken
(exported from RTK Query)
您可以使用skipToken(从RTK查询中导出)
api.useGetCartProductsQuery(user ? user.id : skipToken)
更多回答
我是一名优秀的程序员,十分优秀!