Home > Net >  react.js : fetched data is undefined outside of api folder
react.js : fetched data is undefined outside of api folder

Time:05-05

I am trying to make a web application using Motorcycle Specs Database API from rapidAPI.

I want to export fetched data from index.js to App.js so that I can use the data in the app. But, when I try to console.log the fetched data in componentDidMount function in App.js, it is undefined. I don't know why at the moment, can you see why??

/api/index.js

import axios from "axios";

const options = {
  method: 'GET',
  url: 'https://motorcycle-specs-database.p.rapidapi.com/model/make-name/Yamaha',
  headers: {
    'X-RapidAPI-Host': 'motorcycle-specs-database.p.rapidapi.com',
    'X-RapidAPI-Key': 'MYAPIKEY'
  }
};

export const fetchData = async ()=>{
    await axios.request(options).then(function (response) {
        console.log(response.data);
        return response.data;
    }).catch(function (error) {
        console.error(error);
    });

}


App.js

import logo from './logo.svg';
import './App.css';
import {fetchData} from './api/index';
import React, {Component} from 'react';

class App extends React.Component{
  state = {

    data:[],
  }

  async componentDidMount(){
    const fetchedData = await fetchData();
    console.log('fetchedData is like this',fetchedData);
    this.setState({data:fetchedData});
  }


render(){
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

}
  

 
  

export default App;


CodePudding user response:

Use try/catch instead of chaining then and catch to your promise:

export const fetchData = async () => {
 try{
     const { data } = await axios.request(...); 
     return data;
  } catch (errors) {
    console.log(errors);
  }   
}
  • Related