Jayakumar Thangavel
Jayakumar Thangavel

Reputation: 2007

How to call API inside React function component?

I have a scenario like need to call API inside the React function component. If possible how to return the result. I could be able to call the API but the response is available in the variable. Please advise

My sample code

import React from 'react';
import ReactTable from 'react-table'
import 'react-table/react-table.css'
import axios from 'axios';

const Table = (props) => {
  const getData = [axios.get("https://lq-time- 
    tracking.firebaseio.com/user.json").then(function(response) {
        console.log(response);
      }).catch(function(error) {
        console.log(error);
      })]    

 const data = [{getData}];       
 const columns = [{
    id: 'Name',
    Header: 'Name',
    accessor: data.user
  }, {
    Header: 'Date',
    accessor: 'Date',
  }, {
    Header: 'Comment',
    accessor:'Comment' 
  }]

  return <ReactTable
    data={...data}
    columns={columns}
    pivotBy={ ['Date', 'Name']}
  />
}       
export default Table;

Upvotes: 1

Views: 3869

Answers (2)

Arvind
Arvind

Reputation: 70

componentDidMount() {
   fetch("https://api.example.com/items")
     .then(res => res.json())
     .then(
       (result) => {
         this.setState({
           isLoaded: true,
           items: result.items
         });
       },
       // Note: it's important to handle errors here
       // instead of a catch() block so that we don't swallow
       // exceptions from actual bugs in components.
       (error) => {
         this.setState({
           isLoaded: true,
           error
         });
       }
     )
 }

Upvotes: 0

Nick
Nick

Reputation: 16576

You'll likely want to use a couple hooks; useEffect to do the API querying and useState to store the data. The empty dependency array in the useEffect hook will make sure the API call is only made when the component mounts. Then, when the call resolves, the data is set to a stateful variable called data.

import React, { useEffect, useState } from 'react';
import ReactTable from 'react-table'
import 'react-table/react-table.css'
import axios from 'axios';

const Table = (props) => {
  const [data, setData] = useState({});

  useEffect(() => {
    axios.get("https://lq-time-tracking.firebaseio.com/user.json")
      .then(function(response) {
        setData(response.data);
      }).catch(function(error) {
        console.log(error);
      })
  }, []);

  const columns = [{
    id: 'Name',
    Header: 'Name',
    accessor: data.user
  }, {
    Header: 'Date',
    accessor: 'Date',
  }, {
    Header: 'Comment',
    accessor:'Comment' 
  }]

  return <ReactTable
    data={...data}
    columns={columns}
    pivotBy={ ['Date', 'Name']}
  />
}

export default Table;

Upvotes: 4

Related Questions