简体   繁体   English

如何使用 axios 从 openweathermap 调用当前温度

[英]How to call current temperature from openweathermap with axios

I am trying to do an axios call to get the latest temperature using openweatherapi.我正在尝试拨打 axios 电话以使用 openweatherapi 获取最新温度。 However for some reason I cant find out why my axios call is not working.但是出于某种原因,我无法找出为什么我的 axios 呼叫不起作用。 Any help would be great, here is my code:任何帮助都会很棒,这是我的代码:

function Overview() {
    const appState = useRef(AppState.currentState);
    const [count, setCount] = useState(0);
    const [active, setActive] = useState(false);
    const [latitude, setLatitude] = useState(0);
    const [longitude, setLongitude] = useState(0);
    const [temperature, setTemperature] = useState('');
    const API_KEY = '{apikey}';

    const getLocationAsync = async () => {
        let {status} = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            console.log('Location Permission Error')
        }

        const loc = await Location.getCurrentPositionAsync({});

        setLatitude(loc.coords.latitude);
        setLongitude(loc.coords.longitude);
    }

    const getTemperature = async () => {
        const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
        const response = await axios.get(encodeURI(url));
        const temp = await response.data?.main?.temp;
        setTemperature(temp);
    }

    useEffect(() => {
        appState.current.match('active') ? setActive(true) : setActive(false)
        active && setInterval(() => setCount((oldCount) => oldCount + 1), 60000);
        getLocationAsync();

        return () => {
            clearInterval();
        };
    }, [active]);

    useEffect(() => {getTemperature()}, [longitude, latitude])

    return (
        <View style={{margin: 32}}>
            <View style={{marginBottom: 32}}>
                <Text style={{fontSize: 36, fontFamily: 'Roboto_400Regular'}}>Great!</Text>
                <Text style={{fontSize: 16, color: '#878787', fontFamily: 'Roboto_400Regular'}}>Average mood 23%</Text>
            </View>
            <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                <OverviewContainer title="Weather" value={temperature ? temperature : "no data"} />
                <OverviewContainer title="Time on app" value={secondsToHms(count)} />
            </View>
        </View>
    );
}

Any advice on what im doing wrong would be great!关于我做错了什么的任何建议都会很棒!

You should change your getWeather function to the following.您应该将getWeather function 更改为以下内容。

const getWeather = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${api_key}`);
    setData(response.data.main.temp);
};

You can get the data using encodeURI() function.您可以使用encodeURI() function 获取数据。

const getWeather = async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}`;
    const response = await axios.get(encodeURI(url));
    const temp = await response.data?.main?.temp;
    setData(temp);
}

You can call your getWeather function like below:您可以像下面这样调用您的 getWeather function:

const getWeather = () => {
             axios.get(`https://api.openweathermap.org/data/2.5/weather? 
                  lat=${latitude}&lon=${longitude}&appid=${api_key}`)
            .then((response)=>setData(response.data.main.temp))
            .catch((err)=> consol.log(err))
                         }
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM