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

98
Visualizações
Fetch is returning an empty array with template string

My useState value of city, default London, isn't working with the fetch value URL being called in my getWeather function. It runs sometimes when I accidentally re-render the code but not any time else

import './App.css';
import Daily from './components/daily';
import {useState, useEffect} from 'react'

function App() {

const [city, setCity] = useState('London')
const [weatherData, setWeather] = useState([])

const getWeather = async() =>{
  try{
    const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=f8d957da06af592a1390c360ea801908&units=metric`)
    const pResp = await resp.json()
    setWeather(pResp)
  }
  catch{
    console.log('error')
  }
}

useEffect(()=>{
  getWeather()
},[])
  return(
    <>
    <Daily {...weatherData}></Daily>
    </>
  )
}

export default App;
 code here
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem was that the weatherData was being passed through before it fetched and formatted properly, to fix that I just added a loading screen and render delay so the data is always there New Code

import './cssdirect/App.css';
import Daily from './components/daily';
import {useState, useEffect} from 'react'
import Loading from './Loading';

function App() {
const [loading, setLoading] = useState(true)
const [city, setCity] = useState('paris')
const [weatherData, setWeather] = useState([])

const getWeather = async() =>{
  setLoading(true)
  try{
    const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=f8d957da06af592a1390c360ea801908&units=imperial`)
    const pResp = await resp.json()
    setWeather(pResp)
    setLoading(false)
  }
  catch{
    console.log('error')
  }
}



useEffect(()=>{
  getWeather()
},[])

  if(loading==true){
    return <Loading/>
    
  }
  else{
    return <Daily {...weatherData}/>
    
  }
}

export default App;
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