1

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;

2 Answers 2

4

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;

Sign up to request clarification or add additional context in comments.

Comments

0
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
         });
       }
     )
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.