1
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.

1
  • Did the Api call happened ? what was the result of the api call? Commented Jan 14, 2020 at 4:16

2 Answers 2

1

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

}

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

1 Comment

res.json() doesn't return a promise, does it?
0

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.

3 Comments

Still getting null data
It depends on how fetch function is written. If it is not returning any promise, then it will indeed not return the expected result.
I've tested this code with another service that returns json data, so I'm confident the code works as expected. Have you verified the response from the server is JSON 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.