React Query获取数据报错:Cannot read properties of null (reading 'token')
React Query结合AuthContext获取数据的问题处理
问题背景
我在项目中使用React Query从后端获取数据,同时通过AuthContext在应用初始化时从localStorage读取Token并分发,以此在整个应用中共享用户上下文。
核心问题
当使用依赖用户上下文的useQuery钩子获取数据时,数据获取完成后抛出错误:
Cannot read properties of null (reading 'token')
尝试过程与新问题
添加用户存在的判断条件后,又出现新错误:
Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ['user']
推测是dispatch更新user值存在延迟导致的。我知晓可直接从localStorage读取Token,但希望通过AuthContext实现这一逻辑。
临时解决方案
使用useRef钩子将useQuery的enabled初始设为false,当检测到user存在时,再将enabled设为true,以此控制查询的执行时机。
内容的提问来源于stack exchange,提问作者abdullah bouladame
相关产品推荐
相关产品推荐

