1

I'm receiving an array of numbers from an API, but when I use methods on it, the array returns empty.

When I log an example array and the API array, the two have a different format(See in below image)

two array with different content

The second array is from an API with a length of 20, when I try to slice it to 3, it returns in the same format but empty.

The example array and API array when expanded log something like below

The example array and API array when expanded

When I try to slice them using:

exampleArr.slice(0,3)
apiArr.slice(0,3)

They log following

Array when slice apply

Any help would be greatly appreciated.

yajiv
  • 2,901
  • 2
  • 15
  • 25
J.Price
  • 15
  • 4
  • Could the API be coming back as JSON that would need to be parsed before running array functions on it? – Tyler Sells Sep 24 '18 at 14:34
  • Could you show us the raw text the API returned? Is it valid JSON? – Shilly Sep 24 '18 at 14:36
  • Please show more code. It looks like you're slicing the array when it's still empty, and since the console will live update logged objects, it can be confusing. Example code that reproduces this: https://jsfiddle.net/khrismuc/a0t91yj3/ –  Sep 24 '18 at 14:37
  • Not flagging it yet, but most likely a dupe of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –  Sep 24 '18 at 14:41
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  Sep 24 '18 at 15:25

2 Answers2

1

When I log an example array and the API array, the two have a different format

They have the same format. Your "two" is just an empty array.

yaru
  • 1,260
  • 1
  • 13
  • 29
1

Your code is correct, but I think your array on initial load page is empty and after getting the response of API fills it, you should use Promise or waiting for the response by setTimeout.

    return new Promise(
         function (resolve, reject) {
          ////////////////Your APi/////////
          axios.get('/sample', (response)=>{
       if(response.state === 'success')
           ////// Do slice on array ////
           let doSlice = apiArr.slice(0,3);
           resolve(apiArr.slice(0,3)); // resolve
         } else {
           reject(reason); // reject
         }
      })
      )

Or

  setTimeout(function(){
     apiArr.slice(0,3);
  },1000)
Hozhabr
  • 454
  • 2
  • 9