1

I'm trying to get data from an API using axios command like

function fetchData(apiURL){
    let data = [];
    let options = {
        method: "GET",
        url: apiURL,
        headers: {
            "Access-Control-Allow-Origin": "*"
        },
        credentials: "include"
    };

    axios(options)
        .then(response => {
            data = response.data;
            console.log(data);
        })
        .catch(function (error) {
            console.log("System error : " + error);
        });

    return data;
}

but that will produce sets of arrays which will store arrays of JSONs from response.data in count of 100 per array set.

I haven't had problem using fetch() to retrieve all data. How I can get similar response of one large array of JSON objects instead of a split?

PS. I have triggered that function in the

 componentDidMount() {
        const apiURL = process.env.REACT_APP_API;
        let tableData = fetchData(apiURL);
        console.log("DATA " + JSON.stringify(tableData));
        this.setState({tblData : tableData});
    }

2 Answers 2

1

Axios requests are asynchronous and return promises, so you need to adjust your example a bit so that your function returns a promise.

/**
 * @return {Promise<T>}
 */
function fetchData(apiURL){
    const options = {
        method: "GET",
        url: apiURL,
        headers: {
            "Access-Control-Allow-Origin": "*"
        },
        credentials: "include"
    };

    return axios(options)
        .then(response => {
            return response.data;
        })
 }

Now, when you consume this API do so asynchronously.

function somethingThatUpdatesThatUI() {
    fetchData("/api/foo/bar")
       .then((data) => {
           //perform updates to UI or state here
       })
       .catch((err) => {
           //alert the users that an error has happened here
       })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Looks promising but I need to get it triggered from React componentDidMount(). Before I was calling fetchData there. I have update OP with that
1

You can update the componentDidMount function:

componentDidMount() { 
  const apiURL = process.env.REACT_APP_API; 
  fetchData(apiURL).then(data => { 
    console.log(data ${JSON.stringify(tableData)}) 
    this.setState({tblData : data});
  }) 
} 

1 Comment

Yeah, exactly what I have done based on Robert's answer. On another hand is it better to do that from componentDidMount or componentWillMount? I'm trying to minimize as much as possible displaying empty table before retrieving the data.

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.