-1

I've been searching for a solution for my Problem, it seems actually pretty easy but it doesn't work :(. The problem is the following: I fetch data from my backend which is localhost/users. I get the data and i can console.log them. But it seems impossible for me to write it on a variable and export it. Here is my Code:

import axios from "axios";


function init() {
    let obj;
    axios('/users')
    .then(response => {
        obj = (response.data)
        console.log(obj)
        return obj
    })
    .catch(error => {
        console.log("error fetching")
        return null
    })
    
}

let obj = init()


export default obj

If i try to console.log the exported variable it just writes undefined, i guess it skips the response section. The returned Variable is undefined too

jauki
  • 149
  • 1
  • 5

2 Answers2

0

You cannot return the value from the inner function.

To do that you can use Promises or Callback or simply React setState if you want to but it inside the component.

Using Promises:

import axios from "axios";


function init() {
    return new Promise((resolve, reject) => {
     axios('/users')
      .then(response => {
        obj = (response.data)
        resolve(obj);
      })
      .catch(error => {
        reject(error);
      })
   });
}

// To log or get the values 
init().then(obj => {
  console.log(obj);
}).catch(error => console.log(error));


export default obj

Using Callbacks

import axios from "axios";


function init(successCallback, errorCallback) {
     axios('/users')
      .then(response => {
        obj = (response.data)
        successCallback(obj);
      })
      .catch(error => {
        errorCallback(error);
      })
}

// To log or get the values 
init(obj => {
  console.log(obj);
}, error => {
  console.log(error);
});


export default obj
Wael Zoaiter
  • 686
  • 1
  • 7
  • 21
0

You just need to add return keyword before axios function

import axios from "axios";


function init() {
 let obj;
 return axios('/users')
 .then(response => {
     obj = (response.data)
     console.log(obj)
     return obj
 })
 .catch(error => {
     console.log("error fetching")
     return null
 })
 
}

let obj = init()


export default obj
 ```