I have a functional component which renders a patient's information. In the component, 3 actions are being dispatched in the useEffect hook, as shown below. Each action is making an async network request.
useEffect(()=>{
dispatch(fetchInpatient(patient_id));
dispatch(fetchAllDoctors());
dispatch(fetchVacantRooms());
}, []);
I am also fetching the state using useSelector as such:
const inpatient = useSelector(state => state.inpatient.inpatient);
const doctors = useSelector(state => state.doctors.doctors);
const vacantRooms = useSelector(state => state.vacantRooms.vacantRooms);
My return code is dependant on these 3 fetched states. So, it looks like this:
if(inpatient && doctors && vacantRooms){
//render user info
}
else{
//render loading icon
}
Now, initially inpatients, doctors and vacantRooms are filled with the default state or the previous state. But when all the actions are dispatched and the state is updated, useSelector does not re-render my component so it displays the previous patient's information until i manually refresh the page. What is the work-around for this? What am i doing wrong?
These are my reducers:
export default (state = {} , action) => {
switch(action.type){
case 'FETCH_INPATIENT':
return {...state , inpatient: action.payload};
default:
return state;
}
}
export default (state = {} , action) => {
switch(action.type){
case 'FETCH_ALL_DOCTORS':
return {...state , doctors: action.payload};
default:
return state;
}
}
export default (state = {} , action) => {
switch(action.type){
case 'FETCH_VACANT_ROOMS':
return {...state , vacantRooms: action.payload};
default:
return state;
}
}
All of these are in separate files. My reducers/index is as such:
import{ combineReducers } from 'redux';
import inpatientsReducer from './inpatientsReducer';
import inpatientReducer from './inpatientReducer';
import allDoctorsReducer from './allDoctorsReducer';
import vacantRoomsReducer from './vacantRoomsReducer';
export default combineReducers({
inpatients: inpatientsReducer,
inpatient: inpatientReducer,
doctors: allDoctorsReducer,
vacantRooms: vacantRoomsReducer
});
My fetchInpatient(id) action creater is as:
export const fetchInpatient = (inpatient_id) => {
return async (dispatch) => {
const response = await axios.post('http://localhost:3001/api/inpatients/display' , {inpatient_id});
dispatch({
type: 'FETCH_INPATIENT',
payload: response.data
})
}
}