Home > OS >  Invalid hook call. Hooks can only be called inside of the body of a function component
Invalid hook call. Hooks can only be called inside of the body of a function component

Time:12-20

I am trying to display current temperature of Halifax city using api key. But when I run the the code it throws error 'Invalid hook call. Hooks can only be called inside of the body of a function component'.

Below is my code which is used to display the current temperature from api.

 import React, { Component } from 'react';
    import { useEffect, useState } from "react";
    const [data, setData] = useState({})
    const getWetherDetails = (cityName) => {
        if (!cityName) return
        const apiURL = "https://api.openweathermap.org/data/2.5/weather?q="   Halifax   "&appid="   apiKey
        axios.get(apiURL).then((res) => {
            console.log("response", res.data)
            setData(res.data)
        }).catch((err) => {
            console.log("err", err)
        })
    }
    
    
    
    const apiKey = "f56f24967aaf51182d1d4df628297c6d"
    const [inputCity, setInputCity] = useState("")
    export class Counter extends Component {
      static displayName = Counter.name;
    
      constructor(props) {
        super(props);
        this.state = { currentCount: 0 };
        this.incrementCounter = this.incrementCounter.bind(this);
      }
        
      incrementCounter() {
        this.setState({
          currentCount: this.state.currentCount   1
        });
      }
    
      render() {
        return (
          <div>
                
                <br />
                <br />
                <img src="E:\\MCDA\\vs react\\Project1\\Project1\\Capture.PNG"/><br />
                <br />
                <h2><b>I live in Surat.</b></h2><br />
                <br />
                <p>Surat is a city located in Gujarat in India. It is also known as Diamond hub.
                   Surat is also know for its textile market.</p>
                <br />
                <br />
                <img src="E:\\MCDA\\vs react\\Project1\\Project1\\weather.png" /><br />
                <p>- &deg;C</p>
                <h6 className="weathorTemp">{((data?.main?.temp) - 273.15).toFixed(2)}°C</h6>
            </div>
        );
      }
    }

Any help is appreciated. Thanks.

CodePudding user response:

hooks are only allowed inside functional component. you are trying to mix both (class and function component)

make it functional component or either use setState of class component

import React, { Component } from 'react';


const apiKey = "f56f24967aaf51182d1d4df628297c6d"
export class Counter extends Component {
    static displayName = Counter.name;

    constructor(props) {
        super(props);
        this.state = { currentCount: 0, data: {}, inputCity: "" };
        this.incrementCounter = this.incrementCounter.bind(this);
    }

    incrementCounter() {
        this.setState({
            currentCount: this.state.currentCount   1
        });
    }

    getWetherDetails = (cityName) => {
        if (!cityName) return
        const apiURL = "https://api.openweathermap.org/data/2.5/weather?q="   Halifax   "&appid="   apiKey
        axios.get(apiURL).then((res) => {
            console.log("response", res.data)
            this.setState({ re.data })
        }).catch((err) => {
            console.log("err", err)
        })
    }

    render() {
        const { data } = this.state
        return (
            <div>

                <br />
                <br />
                <img src="E:\\MCDA\\vs react\\Project1\\Project1\\Capture.PNG" /><br />
                <br />
                <h2><b>I live in Surat.</b></h2><br />
                <br />
                <p>Surat is a city located in Gujarat in India. It is also known as Diamond hub.
                    Surat is also know for its textile market.</p>
                <br />
                <br />
                <img src="E:\\MCDA\\vs react\\Project1\\Project1\\weather.png" /><br />
                <p>- &deg;C</p>
                <h6 className="weathorTemp">{((data?.main?.temp) - 273.15).toFixed(2)}°C</h6>
            </div>
        );
    }
}

CodePudding user response:

Since hooks are allowed in the functional components only, we can use state for storing the required data in class based components.

I have updated the code according to the class based component.

please use the debounce while making api call, which will increase efficiency of making api calls.

import React, { Component } from 'react';
// Move these keys to config file
const apiKey = "f56f24967aaf51182d1d4df628297c6d" 

export class WetherDetails extends Component {
static displayName = Counter.name;

constructor(props) {
    super(props);
    this.state = { 
        currentCount: 0,
        data: {},
        inputCity: ""
    };
    this.incrementCounter = this.incrementCounter.bind(this);
    this.getWetherDetails = this.getWetherDetails.bind(this);
}

incrementCounter() {
    this.updateState({ currentCount: this.state.currentCount   1 });
}

updateState(newstate) {
    this.setState((prevState) => ({
        ...prevState,
        newstate,
    }));
}

getWetherDetails(cityName) {
    if (!cityName) return
    const apiURL = "https://api.openweathermap.org/data/2.5/weatherq="   cityName   "&appid="   apiKey
    axios
        .get(apiURL)
        .then((res) => {
            console.log("response", res.data)
            this.updateState(res.data)
        }).catch((err) => {
            console.log("err", err)
        })
}

updateCity(e) {
    this.updateState({ inputCity: e?.target?.value })
    // use debounce to call the getWetherDetails
    //
}

render() {
return (
    <div>
        <input type={"text"} onChange={this.updateCity} />
        <br />
        <br />
        <img src="E:\\MCDA\\vs react\\Project1\\Project1\\Capture.PNG"/><br />
        <br />
        <h2><b>I live in Surat.</b></h2><br />
        <br />
        <p>Surat is a city located in Gujarat in India. It is also known as Diamond hub.
            Surat is also know for its textile market.</p>
        <br />
        <br />
        <img src="E:\\MCDA\\vs react\\Project1\\Project1\\weather.png" /><br />
        <p>- &deg;C</p>
        <h6 className="weathorTemp">{((data?.main?.temp) - 273.15).toFixed(2)}°C</h6>
    </div>
);
} }
  • Related