使用RTK Query发送Get请求返回undefined,Redux Persist存本地问题
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
Authorizationheader contains the correctBearer <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

