Home > Software design >  i cannot access the value inside a function
i cannot access the value inside a function

Time:08-11

Here is my code :

let namesList = ref([]);

const GetFormData = (payload) => {
  return new Promise((resolve, reject) => {
    api
      .get("api.php", { params: { search: payload } })
      .then((response) => {
        data.value = response.data;

        // console.log(data.value);
        // convert array objects to array strings
        namesList = data.value.map(function (list) {
          return list["first_name"];
        });
        // console.log(namesList);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

If I console the namelist inside the function it returns the value :

(9) ['Michael Angelodfsed', 'Mardin', 'Joemar', 'Chirs', 'chan', 'loys', 'Lorena', 'kayabusa', 'kayabusa']
0: "Michael Angelodfsed"
1: "Mardin"
2: "Joemar"
3: "Chirs"
4: "chan"
5: "loys"
6: "Lorena"
7: "kayabusa"
8: "kayabusa"
length: 9
[[Prototype]]: Array(0)

but if I console the variable outside the function it gives me this console.log(nameList);

RefImpl {__v_isShallow: false, dep: undefined, __v_isRef: true, _rawValue: Array(0), _value: Proxy}
dep: Set(1) {ReactiveEffect}
__v_isRef: true
__v_isShallow: false
_rawValue: []
_value: Proxy
[[Handler]]: Object
[[Target]]: Array(0)
[[IsRevoked]]: false
value: (...)
[[Prototype]]: Object

please help me guys. really struggling here. really appreciate your help.

CodePudding user response:

Follow this:

consf nameList = ref([])

console.log(nameList.value) // get value
nameList.value = ["Shin"] // set value 

CodePudding user response:

As @Deepak stated, you are trying to access the variable before the function (the api call) ends. Your namesList is a ref object, so when you log it before it ends, it logs the object.

As your function is calling an api and use a Promise, you can change your function code to this:

const GetFormData = (payload) => {
  return new Promise((resolve, reject) => {
    api
      .get("api.php", { params: { search: payload } })
      .then((response) => {
        data.value = response.data;

        // console.log(data.value);
        // convert array objects to array strings
        namesList = data.value.map(function (list) {
          return list["first_name"];
        });
        // console.log(namesList);
        resolve(namesList);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

GetFormData(payload).then(data => console.log(data))
  • Related