0

I don't know if this is a "gotcha" or a bug in Javascript, React-native, or a combination thereof. Some basics about the React-native app: it uses react-redux, redux-persist, and redux-thunk.

I have a fetch that is polling in the background and fetching updates for objects in the app. The API endpoint returns a 304 when no data has changed, and when data has changed it returns an array of updated objects. The basics look like this:

fetchSecure('/objects?filter=all&since='+lastPoll, apiToken, {method: 'GET'})
      .then(response => {
        if(response.status==200) {
          response.json().then(json => { // this is a promise!
            console.log(json) // this logs an empty array
            console.log('Found '+json.length+' new objects') // this logs "1 new objects"
            dispatch(updateObjects(json, true))
          })
        } else {
          console.log('Completed poll: no changes')
        }
      })
      .catch(error => console.log(error))

So as the comments state, if I perform a console.log(json) it returns an empty array. However, if I log the same thing again and call .length on json it returns the number of updated objects.

If I use lodash and perform a console.log(_.clone(json)) it then gives me the actual array expected. However, it doesn't seem to maintain its "readability" downstream in the code.

I am left unable to debug what happens downstream because my logging statements stop working. What is causing this behavior? Is this something to do with redux-thunk or an improper implementation of promises?

crockpotveggies
  • 12,682
  • 12
  • 70
  • 140
  • Sounds like `updateObjects` empties the array, and [the console is confusing you](http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) – Bergi Mar 07 '16 at 09:32
  • @Bergi Are you suggesting that the first `console.log` has been deferred until the Promise finishes? – crockpotveggies Mar 07 '16 at 17:59
  • Of course it is, you've put it in the callback… But regardless, can you show us the code of `updateObjects`? – Bergi Mar 07 '16 at 18:01
  • @Bergi Both `console.log` statements are in the callback, so I don't understand you there? However, I've since fixed an issue downstream (in `updateObjects`) that did indeed empty the array and I solved it by cloning the array. The code is a giant monolith, so I'll hold off on posting it unless necessary. If you want to post an answer saying exactly what you did in your first comment I'll be happy to accept it – crockpotveggies Mar 07 '16 at 18:05

0 Answers0