Search code examples
reactjsreduxreact-reduxstatestore

Updating the state with fetched data but when trying to console.log it gives 'undefined'


When I fetch data on render or on change of some dependencies it updates in Redux store properly but when console.loging it gives 'undeifined'.

I am developing booking system and want to fetch already booked hours on specified day

/// Fetch data on render the component and try to console.log
     useEffect(() => {
    axios
      .get(
        `http://localhost/healthboyz/index.php/booked/${
          formData.doctor_id
        }/${moment(formData.date).format('YYYY-MM-DD')}`
      )
      .then((res) => setBookedHrs(res.data))
      .then(() => console.log(bookedHrs))
      .catch((e) => console.log(e));}, 
    [formData.doctor_id, formData.date]);
/// Hours reducer 
 const hoursReducerDefaultState: {
  bookedHrs: string[];
} = {
  bookedHrs: [],
};

export const hoursReducer = (
  state = hoursReducerDefaultState,
  action: {
    type: string;
    data: string[];
  }
) => {
  switch (action.type) {
    case 'SET_BOOKED_HRS':
      return [...action.data];
    default:
      return state;
  }
};


Solution

  • The issue here is actually to do with how the state is being set in Redux:

    Assuming that the hoursReducer is responsible for the whole of hoursReducerDefaultState which is:

    type HoursReducer = {
      bookedHrs: string[];
    };
    
     const hoursReducerDefaultState: HoursReducer = {
      bookedHrs: [],
    };
    

    You then need to set the Redux state to update state you are aiming to update:

    export const hoursReducer = (
      state = hoursReducerDefaultState,
      action: {
        type: string;
        data: string[];
      }
    ) => {
      switch (action.type) {
        case 'SET_BOOKED_HRS':
          // Remember to include the previous state using the "spread" operator
          return {
            ...state,
            bookedHrs: action.data
          }
        default:
          return state;
      }
    };
    

    Note: I'm also assuming that you want to fully replace the value of bookedHrs.