0

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 :/
  }, []);
phoique
  • 97
  • 3
  • 7

2 Answers2

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

Your props will update only in the next event loop cycle, to use react hooks data updation inside useEffect you need to useReducer https://reactjs.org/docs/hooks-reference.html#usereducer

gandharv garg
  • 1,781
  • 12
  • 17
0

[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

costal oktopus
  • 319
  • 2
  • 12