0

Hello guys, I am trying to get Data in My React Component By Calling an API By Using fetch function. I have the folder structure like Below.

1) src->components(All of my components placed here.)

2) src->services(file which contain functions to call API.)

Below is my component, Where i am calling the function from services file to get API Data.

import React from 'react';
import {getApiData} from '../services/';

class Dashboard extends React.Component {
  constructor(){
    super();
    this.state={
      result:''
    }
  }
  componentDidMount(){
    const data =  getApiData();
    console.log(data);
  }
  render(){
    return(
     <div></div>
    );
  }
}

export default Dashboard;

And Below is my code of services file to get the data from API & then return it.

  export function getApiData(){
    fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then((data)=>data.json())
    .then((res)=>res)
  }

And When i console to my fetch function, used in services file. I got the following result.

Promise {pending}
proto: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: undefined
VM370:3 {userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit↵suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto"}

Note: I don't want to use axios.

1 Answers1

0

in your code getApiData is promise but you just call it in component did mount first change the getApiData so we add return to it :

 export function getApiData(){
     return fetch('https://jsonplaceholder.typicode.com/posts/1')
     .then((data)=>data.json())
     .then((res)=>res)

}

now we can access it in didComponet:

componentDidMount(){
    getApiData().then(data=>{
       console.log(data);

     //or set in state
     this.setState({result:data})
     });
 }
MBehtemam
  • 7,865
  • 15
  • 66
  • 108