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

使用RTK Query调用OpenWeather API返回undefined问题求助

Fix for RTK Query returning undefined with OpenWeather API

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 of long for consistency.
  • Replace YOUR_ACTUAL_API_KEY with your real OpenWeather API key.
  • Removed the trailing ? from baseUrl and 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}> from react-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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:57:50