1

I have this small web app which I wrote when I was studying react, of course its in Class based components

As I learnt more I've decided to move over to hooks but I can't get my mind around it, imo I think class based components was more straightforward

So in Class based components I had my configiration as follows

State:

this.state = { countryData: {updated:0,cases:0, todayCases:0, deaths:0, todayDeaths:0, recovered:0, active:0}}

Setting initial state:

async getData(){
        const resApi = await Axios.get('https://corona.lmao.ninja/v2/all')
        this.setState({ countryData : resApi.data })
}

componentDidMount(){ this.getData() }

And then I have a dropdown menu of options which on change changes the country data

async getCountryData(event){
        if (!event) return this.getData()
        const res = await Axios.get(`https://corona.lmao.ninja/v2/countries/${event.value}`)
        this.setState({ countryData : res.data })
}

So now I've tried to make the same thing in hooks I've started with

const [countryData, setcountryData] = useState({updated:0,cases:0, todayCases:0, deaths:0, todayDeaths:0, recovered:0, active:0})

Then for the previous 2 methods

    const useChoosenCountry = (event) => {
        useEffect(() => {
            async function getdata(event){
                if (!event) {
                    const resApi = await Axios.get('https://corona.lmao.ninja/v2/all')
                    setcountryData(resApi.data)
                }
                    const res = await Axios.get(`https://corona.lmao.ninja/v2/countries/${event.value}`);
                    setcountryData(res.data);   
                } 
                console.log(event)
            getdata()
        },[event])
    }

But it looks like I'm really far it's not console logging the event on change

Ahmed Zaki
  • 23
  • 5

1 Answers1

1

componentDidMount can be replaced with useEffect(function, []):

useEffect(() => {
    getData();
}, [])


const getData = async () => {
    const res = await Axios.get('https://corona.lmao.ninja/v2/all')
    setcountryData(res.data)
}

const getCountryData = async (event) => {
    if (!event) return this.getData()
    const res = await Axios.get(`https://corona.lmao.ninja/v2/countries/${event.value}`)
    setcountryData(res.data)
}
HermitCrab
  • 3,194
  • 1
  • 11
  • 10