Home > database >  why am I getting an error in fetching data here?
why am I getting an error in fetching data here?

Time:08-08

I have this for saving fetched data in state:

import React, {useState, useEffect, createContext} from 'react';


import { getLocation } from '../api';

export const LocationContext = createContext();

const LocatonContextProvider = (props) => {

const [location, setLocation] = useState({})

useEffect(() => {
    const fetchAPI = async () => {
        setLocation(await getLocation());
    }

    fetchAPI();
}, [])


return (
    <LocationContext.Provider value={location}>
        {props.children}
    </LocationContext.Provider>
);
};

export default LocatonContextProvider;

and this for saving weather data import React, {useState, useEffect, createContext, useContext} from 'react';

 //api
 import { getWeather } from '../services/api';

//Context
import { LocationContext } from '../contexts/LocationContextProvider';

export const WeatherContext = createContext()

const WeatherContextProvider = ({children}) => {

const location = useContext(LocationContext);
const lat = location.lat;
const lon = location.lon;

const [weather, setWeather] = useState({});

useEffect(() => {
    const fetchAPI = async () => {
        setWeather(await getWeather(lat,lon));
    }
    fetchAPI();
}, [lat, lon])

return (
    <WeatherContext.Provider value={weather}>
        {children}
    </WeatherContext.Provider>
);
};

export default WeatherContextProvider;

and here is the axios request: import axios from "axios";

const getLocation = async () => {

const LOCATION_URL = 'http://ip-api.com/json/?fields=country,city,lat,lon,timezone';

const response = await axios.get(LOCATION_URL);
return response.data;
}


const getWeather = async (lat, lon) => {

const WEATHER_URL = `https://api.openweathermap.org/data/2.5/weather? 
lat=${lat}&lon=${lon}&appid=bac9f71264248603c36f011a991ec5f6`;

const response = await axios.get(WEATHER_URL)
return response.data;
}


export {getLocation, getWeather};

When I refresh the page, I get an 400 error and after that I get the data, I don't know why the error occurs

CodePudding user response:

useEffect(() => {
    const fetchAPI = async () => {
        setWeather(await getWeather(lat,lon));
    }
    
    if (lat && lon) {
      fetchAPI();
    }
}, [lat, lon])
  • Related