1

I'm trying to convert an older style react class to a newer function that uses useState and useEffect instead of this.setState and componentDidMount but can't get it to quite work - can anyone help me see what I'm doing wrong - finding hooks quite confusing - thanks

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

const App = function() {
  function  getWeather(){
      fetch('https://api.openweathermap.org/data/2.5/weather?q=London&appid=6e93b3d15872f914c6929fed9ea71e9a')
        .then(data => data.json())
        .then(data => {
            return data
        })
  
  }
  const[weatherData,setData] = useState(getWeather())

  useEffect(()=>{
    setData(getWeather)
  },[])
  
    
    return(<div>
    
    {weatherData.main.temp}
    
    </div>)
  
}

export default App;
skyboyer
  • 22,209
  • 7
  • 57
  • 64

1 Answers1

1

Please try like this.

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

const App = function() {
  function  getWeather(){
      fetch('https://api.openweathermap.org/data/2.5/weather?q=London&appid=6e93b3d15872f914c6929fed9ea71e9a')
        .then(data => data.json())
        .then(data => {
            setData(data);
        })
  
  }
  const[weatherData,setData] = useState([])

  useEffect(()=>{
    getWeather();
  },[])
  
    
    return(<div>
    
    {weatherData.main?weatherData.main.temp:""}
    
    </div>)
  
}

export default App;
BTSM
  • 1,585
  • 8
  • 12
  • 26