0

I'm using Reactjs and want to return an object to another .jsx file coming from a fetch request. I'm a NOOB and for the last 4 days have been trying many permutations based on what I've read on stackoveroverflow and nothing has worked. (Yes, I know "obj" doesn't in the code below doesn't do anything. It's just my last round of trying something new.) Basically, I have a file called Getdata.jsx (the code below) and want it to return to another .jsx file an object containing values derived from a call to an api. The console.log works correctly (no surprise as it is inside a Promise). Here is my current iteration, which also fails:

var obj;

async function pullAPI() {
  fetch("http://localhost:5000/api/customers", { method: "get" })
    .then((res) => res.json())
    .then((data) => (obj = data))
    .then(() => console.log(obj));
}

async function myCall() {
  const info = await pullAPI();
  return info;
}

var Getdata = myCall();

export default Getdata;
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
mystclue
  • 17
  • 5
  • https://www.robinwieruch.de/react-fetching-data – Xesenix Jul 31 '20 at 00:52
  • If I understand you correctly. Do you want to pass data from one component to another? – Cyrus Zei Jul 31 '20 at 00:54
  • 1
    Your `pullAPI` function doesn't `return` anything. In addition to returning the promise chain, you also will need to `return` the value from the last `then` callback. (And in general you should avoid the global `obj`) – Bergi Jul 31 '20 at 01:28
  • "*I want it to return an object*" - not possible. You can return a promise for the object only. – Bergi Jul 31 '20 at 01:29
  • Yes, I want to pass data from one component to another. i'm using chart.js in another component to create a bar graph, and I want to manipulate the data coming from the api before I create the chart. If Bergi is correct about not being able to pass an object, then I'm out of luck with my current design. Yes, my pullAPI isn't returning anything, but it sounds like that doesn't matter as you can't pass an object to another component...I'm frustrated that there isn't a straightforward way of doing this – mystclue Jul 31 '20 at 03:29

0 Answers0