使用RTK Query调用OpenWeather API返回undefined问题求助
The core issue is that your getWeather endpoint's query function expects three separate parameters, but RTK Query hooks only pass one single argument to the query function. When you tried passing three values to useGetWeatherQuery, only the first value was received, leaving the others undefined—resulting in an invalid API request that returns no data. When you switched to passing an object, the query function still tried to treat that object as the first parameter (lat), leading to a malformed URL.
Here's how to fix this:
Step 1: Update the API endpoint to accept an object parameter
Modify the query function to destructure a single object containing all required parameters:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react' export const weatherApi = createApi({ reducerPath: 'weatherApi', // Remove trailing ? from baseUrl for cleaner concatenation baseQuery: fetchBaseQuery({ baseUrl: 'http://api.openweathermap.org/data/2.5/weather' }), endpoints: (builder) => ({ getWeather: builder.query({ // Destructure the object to get lat, lon, units query: ({ lat, lon, units }) => `?lat=${lat}&lon=${lon}&units=${units}&appid=YOUR_ACTUAL_API_KEY`, }), }), }) export const { useGetWeatherQuery } = weatherApi
Notes:
- Use
lon(standard OpenWeather parameter name) instead oflongfor consistency. - Replace
YOUR_ACTUAL_API_KEYwith your real OpenWeather API key. - Removed the trailing
?frombaseUrland added it at the start of the query string to avoid potential double??issues.
Step 2: Call the hook with a correctly structured object
Pass an object matching the properties expected by the query function:
const { data, error, isLoading } = useGetWeatherQuery({ lat: 29.7, lon: -95, units: 'Imperial' }) console.log(data) // Should now return valid weather data
Step 3: Verify error handling
If data is still undefined, check the error object returned by the hook. It will contain details about why the request failed (e.g., invalid API key, malformed URL, network issues):
if (error) { console.error('API Error:', error) }
Additional Checks
- Ensure your Redux store is properly wrapped around your React app. Your root component should be wrapped with
<Provider store={store}>fromreact-redux(this is required for RTK Query to function). - Confirm your API key is valid and has access to the OpenWeather Current Weather Data endpoint.
内容的提问来源于stack exchange,提问作者TheGabbanator

