soubhagya pradhan
soubhagya pradhan

Reputation: 547

Getting returned API result in different function in ReactJS

export function getNodeChartFilteredData(ChartContent, value) {
    let abs = "primary"
    let url = `http://127.0.0.1:8000/api/v1/home/get_node_chart_data_people?abs=${abs}`;
    fetch(url)
    .then(res => res.json())
    .then(res => {
        return res
    })
}


res = getNodeChartFilteredData()
console.log(res)

In ReactJS how can I get returned API result after complete in a different function?

My function is in utils so I want to call this function from different files.

I am always getting null data when I tried.

Upvotes: 1

Views: 46

Answers (2)

Christian Fritz
Christian Fritz

Reputation: 21384

The issue is one of asynchronicity. The Promise of fetch resolves in a different scope than the function you are trying to return something from. Could you structure your logic like this instead? This should work.

export function getNodeChartFilteredData(ChartContent, value) {
    let abs = 'primary';
    let url = `http://127.0.0.1:8000/api/v1/home/get_node_chart_data_people?abs=${abs}`;
    return fetch(url)
      .then(res => res.json())
}

getNodeChartFilteredData()
  .then(res => {
    console.log(res)
  });

This returns the promise so you can act on its resolution (then) in the calling scope. Alternatively you could pass a callback to getNodeChartFilteredData, but it's not good practice to mix promise based logic with old-school callbacks.

Upvotes: 0

Bilal Hussain
Bilal Hussain

Reputation: 572

Assuming that your API works correctly you are not chaining promises correctly

export function getNodeChartFilteredData(ChartContent, value) {
let abs = "primary"
let url = `http://127.0.0.1:8000/api/v1/home/get_node_chart_data_people?abs=${abs}`;
fetch(url)
.then(res => res.json()
.then(res => {
    return res
}))

}

Upvotes: 1

Related Questions