You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用RTK Query发送Get请求返回undefined,Redux Persist存本地问题

Troubleshooting RTK Query Pending State & Redux Persist Issues

Key Issues & Fixes

1. Remove Invalid Body from GET Request

GET requests should not include a body. Your API definition adds an empty body:{} which may cause the request to fail silently or be rejected by the backend.

Fix:
Modify the getUserdata endpoint in your API definition:

getUserdata: build.query({
    query: ({token}) => {
        return {
            url: '/loggeduser',
            method: 'GET',
            headers: {
                'authorization': `Bearer ${token}`
            }
        }
    }
})

2. Check for Unhandled Errors in Component

You’re not capturing error states, which hides the root cause of the pending request.

Fix:
Update your component to log errors:

const { data, isSuccess, isError, error } = useGetUserdataQuery({ token });

console.log('Query status:', { isSuccess, isError, error });

useEffect(() => { 
  if(data && isSuccess) {
    dispatch(changeUser({ user: data.user }));
  }
  if(isError) {
    console.error('Request failed:', error);
  }
}, [data, isSuccess, isError, error, dispatch]);

3. Fix Invalid Console Log Call

You’re calling useGetUserdataQuery(token) in console.log, which passes a string instead of the expected object. This triggers an extra invalid request and skews your debugging output.

Fix:
Match the console log to your actual query call:

console.log(useGetUserdataQuery({ token }));

4. Inspect Network Request Details

Use your browser’s DevTools Network tab to:

  • Confirm the request is sent to http://127.0.0.1:5000/user/loggeduser
  • Verify the Authorization header contains the correct Bearer <token> value
  • Check the response status code (e.g., 401 for unauthorized, 500 for server error) and body

5. Validate Token Availability on Initial Render

Ensure the token variable is not undefined when the query first runs. If the token comes from persisted state, it may load asynchronously. You can conditionally skip the query until the token is available:

const { data, isSuccess } = useGetUserdataQuery({ token }, { skip: !token });

Additional Notes

  • CORS Check: Even if ThunderClient works, browser CORS policies might block the request. Ensure your backend allows requests from your frontend’s origin.
  • RTK Query Persistence: While you’ve set up extractRehydrationInfo, persisting RTK Query’s cache is optional. If you don’t need to retain cached results between sessions, you can exclude the RTK Query reducer from Redux Persist by removing it from the combined reducers.

内容的提问来源于stack exchange,提问作者randeepsarma24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:55:42