简体   繁体   中英

Invalid hook call React while fetching data from an API

passing country full name at onClick event. here is error

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

export const Country = (name) => {

  const [country, setCountry] = useState([]);
    const requestCountry = (name) => {
      axios(`https://restcountries.eu/rest/v2/name/${name}?fullText=true`)
      .then((res) => 
          // Success handling
          setCountry(res.data))
      .catch((error) => {
          // Error handling
          console.error(error.message);
      }); 
    }

    requestCountry(name)
}

Here is Source of Code Click here to see code

Hooks can be only used inside a Functional Component and not a normal function.

Seems like you are trying to call a Functional Component like normal function with an argument like below.

onClick={() => Country(data.name)}

Instead what you might want to do is, show a list of buttons with country names and then when one of the button is clicked, call a handler function which is the axios API call and then show the response country details or do whatever that you want with those detail data.

To do that, you need to save those responded country detail into a React state. If country detail exists, show the details. If not, show the list.

So, I forked your codesandbox and edit it like this.

https://codesandbox.io/s/country-data-i479e?file=/src/App.js

Well from the error I can see that you have put the Country call inside a event handler onClick.

The truth is that hooks can not be called inside event listeners. If you need to change the state inside a listener you can do that but you will need to call useState outside of a listener and then call setState wherever you need.

That is because React uses order in which you call hooks to remember how execute your component in subsequent calls.

const [state, setState] = useState();

const onClick = () => {
     setState(...);
 } ;

As the previous answers have mentioned, you can use hooks only at functional level and not inside a handler. You just need to move your hook a level up and pass it to your function. Also, as you're not returning anything from the Country function, there's no need to import "React".

I have modified the code: https://codesandbox.io/s/quiet-night-7cdvi

Check console (Added a useEffect in Country.js just for logging, you can remove it).

Some changed done in your code. Here is the link to view code. https://codesandbox.io/s/practical-dust-lk0x7?file=/src/country.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM