1

I am passing down a Redux prop to a component that is sourced from a fetch payload. The payload successfully changes state in my reducer and according to my Redux DevTools the component that I am trying to pass the state down to as a prop successfully receives the prop (an array of objects that is fetched in the action) yet when I console.log the prop or try to do anything with it it shows up as an empty array.

My index reducer:

export default combineReducers({
  cart: cartitemReducer,
  products: productReducer,
})

The fetch action:

export const fetchCart = () => dispatch => {
  fetch('http://localhost:3000/api/v1/cartitems/')
    .then(res => res.json())
    .then(cartjson =>
      dispatch({
        type: 'FETCH_CART',
        payload: cartjson
    }))
}

The reducer:

const initialState = {
  userCart: [],
  cartItem: {}
}

export default function(state = initialState, action) {
  switch(action.type) {
    case FETCH_CART:
      return {
        ...state,
        userCart: action.payload
      };

mapping state to props:

const mapStateToProps = state => ({
  cart: state.cart.userCart
})

When I console.log(this.props.cart) it returns an empty array. Yet my DevTools correctly show the contents of the array under cart.userCart

1 Answer 1

0

It all depends on where you are console.log()-ing. If you run that in componentDidMount(), then you would just get an empty-array because console.log() runs before you complete the fetch-request and update your reducers. componentDidMount() will not trigger again.

However, your code looks to be set-up correctly. You should be able to print your results in componentDidUpdate(), which is triggered anytime you get updated props or state.

componentDidUpdate(prevProps){
  if(prevProps.cart.length !== this.props.cart.length){
    console.log(this.props.cart)
 }
}
Sign up to request clarification or add additional context in comments.

2 Comments

You're exactly right and that's a big YIKES on my part. Was hammering away at this for the good part of an hour. Food deprivation is a killer.... Thanks a lot!
@deejay123 Lool. You're welcome! Gots to eat, food is fuel for the brain and happiness :). If you have any other questions, let me know.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.