Search code examples
reactjsreduxreact-reduxredux-promise-middleware

react props comes blank on first transaction


I am using redux promise middleware. I am trying to pass the value in Propsx to state. Props comes empty in useEffect. How can I transfer the contents of the props to state. Props value comes next.

action:

export function fetchBasket() {
  return dispatch => {
    dispatch({
      type: 'GET_BASKET',
      payload: axios.get('url', {
      })
        .then(response => response.data)
    });
  };
}

reducer:

const initialState = {
  fetching: false,
  error: {},
  basket: []
};

export default (state = initialState, { type, payload }) => {
  switch (type) {

  case types.GET_BASKET_PENDING:
    return {
      fetching: true
    };

  case types.GET_BASKET_FULFILLED:
    return { 
      ...state,
      fetching: false,
      basket: payload.result,
    };

  case types.GET_BASKET_REJECTED:
    return { 
      fetching: false,
      error: payload.result
    };

  default:
    return state;
  }
};

use in Component

useEffect(() => {
    props.fetchBasket();
    console.log(props.basket); // null :/
  }, []);

Solution

  • [enter link description here][1]If you want to have values in your first run(Mount). fetch here ==> useLayoutEffect and this will gives the values in useEffect()[]. [uselayouteffect]: https://reactjs.org/docs/hooks-reference.html#uselayouteffect