0

guys.

I have the following async action creator that dispatches another action creator or returns null depending on the current state. The problem is that it is invariably returning null no matter what the current state is.

// actions.js

export const loadPosts = category => (dispatch, getState) => {
  const currentState = getState()
  const posts = currentState.postsByCategory
  const categoryPosts = posts[category]
  const items = categoryPosts.items

  if(items === []) {
    return dispatch(fetchPosts(category))
  }

  return null
}

As you can see, the action creator dispatching fetchPosts() depends on the value of itemsbeing equal to an empty array. I am testing it providing it an intial state with the following structure:

// initialState
const initialState = {
  postsByCategory: {
    hot: {
      isFetching: false,
      items: []
    }
  }
}

I am obviously not accessing the items property appropriately, but I cannot see where the error in my code is. I am testing this with redux-mock-store, creating an instance of a mockStore, and providing it with initialState. Hope you guys can pinpoint the error in my code. Thanks in advance.

1 Answer 1

3

Your problem lies in the comparison

if(items === [])

In the above code, items will not be === to [] as they both are of different instances. If you want to check if items is empty, please use items.length === 0. Hope that helps.

1
  • hey man, it worked. Thanks! I just don't quite get the difference between === [] and using .length === 0. Does it have anything to do with array metadata? Do you have any suggestion of further reading to get a better grasp of this?
    – h_tm
    Apr 11, 2017 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.