Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
Invalid hook call trying to make an axios get request in react

I'm recreating a simple weather app with react and am having a lot of trouble creating a very simple API call. I've tried a plethora of methods on here, youtube, etc and continuously get errors. The current code I have is:

import Axios from 'axios';
import { Home } from '../components/Home'
import React, {useState, useEffect} from 'react'

var weatherApiRootUrl = 'https://api.openweathermap.org';
var weatherApiKey = 'd91f911bcf2c0f925fb6535547a5ddc9';


//function to generate weather URL. fetches lat/lon and creates new url
function GetWeatherUrl(loc){
  const [weatherLink, setWeatherLink] = useState("");

  const getCoordinates = () => {
    Axios.get(`${weatherApiRootUrl}/geo/1.0/direct?q=${loc}&limit=5&appid=${weatherApiKey}`).then(
      (response)=>{
        console.log(response);
        setWeatherLink(`${weatherApiRootUrl}/data/2.5/onecall?lat=${response.data.lat}&lon=${response.data.lon}&units=imperial&exclude=minutely,hourly&appid=${weatherApiKey}`);
      }
    );
  };
return(
  <div>
    {weatherLink}
  </div>
);
  
}

export{
  GetWeatherUrl
}

The purpose of this file is just to use the user input (a city name designed by variable loc) to fetch lat/lon coordinates of the inputted city as that data is needed for the second link that fetches weather information. The user input is handled from another component and works fine.

All I intend for this code to do is fetch latitude and longitude data using loc and use those numbers to generate the new link that fetches weather data. The weather data will be done with a different api call on another file. The working method of this current file should be useable for the future file meant to fetch weather so this is kind of two birds in one stone.

I need the weatherLink generated to be able to be exported to do this so I would really prefer a solution allowing that please. I originally was going to just export the raw lat/lon data and use them for the call in the new file as how I did with loc here but I decided returning a completed link as a string would maybe be easier. Really would appreciate someone's help on this it's been frustrating me for way longer than it should!

Not really needed but here's the non-react version of the site if it helps: https://giovannimalcolm.github.io/weather-dashboard/

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This can be easily solved without needing to use React at all, since it is not a component and doesn't have any rendering logic in itself per se:

import Axios from 'axios';

const weatherApiRootUrl = 'https://api.openweathermap.org';
const weatherApiKey = 'd91f911bcf2c0f925fb6535547a5ddc9';

export async function GetWeatherUrl(loc) {
    const response = await Axios.get(`${weatherApiRootUrl}/geo/1.0/direct?q=${loc}&limit=5&appid=${weatherApiKey}`);
    return `${weatherApiRootUrl}/data/2.5/onecall?lat=${response.data.lat}&lon=${response.data.lon}&units=imperial&exclude=minutely,hourly&appid=${weatherApiKey}`;
}

Then in places where you need to use the weather URL, you need to remember that GetWeatherUrl returns a promise, so you've got to await it (or handle it like any other promise):

const myFn = async () => {
    const weatherUrl = await GetWeatherUrl(loc);
    const weatherUrlData = await Axios.get(weatherUrl);
};

myFn();
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda