Home > database >  React.js Axios API render error on request
React.js Axios API render error on request

Time:08-01

I am trying to fetch some data from a Football API. For example, the countries that are provided by the API. I could get the data in the console.log but as soon as I try to render it, I get this error : Uncaught TypeError: (0 , axios__WEBPACK_IMPORTED_MODULE_0__.useState) is not a function or its return value is not iterable.

Here is the code :

    import axios from 'axios';
    import './App.css';
    import { useState } from 'axios';
    import React from 'react';
    
    
    function Ui() {
      const [country, setCountry] = useState('')
      
    
      
      const options = {
        method: 'GET',
        url: 'https://api-football-v1.p.rapidapi.com/v3/countries',
        headers: {
          'X-RapidAPI-Key': 'dfcebb8bebmsh0e7af4f6ec73ae0p1b6491jsna7b4674b3981',
          'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com'
        }
      };
      
    
      const getCountry = () => {
      axios.request(options).then(function (res) {
        setCountry(res.data.response);
        
      }).catch(function (error) {
        console.error(error);
      })
    }
    
    
      
    
    
      return (
        <>
        <button onClick={getCountry}>Get Country</button>
        <p>{country}</p>
        </>
      );
    }
    
    export default Ui;

CodePudding user response:

You're trying to import useState from Axios instead of React.Change it to this: import React, {useState} from 'react'; and for Axios: import axios from 'axios'; You're also importing axios twice.

You shouldn't add the api-key here either. You might want to look at your code again.

Example to print all the country names (put in the API key where it says API-KEY):

import axios from "axios";
import React, { useState, useEffect } from "react";

function Ui() {
  const [country, setCountry] = useState([]);

  useEffect(() => {
    axios
      .get("https://api-football-v1.p.rapidapi.com/v3/countries", {
        headers: {
          "X-RapidAPI-Key": "API-KEY"
        }
      })
      .then((res) => {
        setCountry(res.data.response);
      })
      .catch((err) => console.log(err));
  }, []);

  return (
    <>
      <button>Get Country</button>
      <div>
        {country.map((data, i) => (
          <h1>{data.name}</h1>
        ))}
      </div>
    </>
  );
}

export default Ui;
  • Related