60 lines
1.6 KiB
JavaScript
60 lines
1.6 KiB
JavaScript
import { useEffect, useReducer } from "react";
|
|
import { GET_CITY_LISTS } from "@/core/utils/routes";
|
|
import useRequest from "@/lib/hooks/useRequest";
|
|
const ACTIONS = {
|
|
LOADING: "loading",
|
|
SUCCESS: "success",
|
|
ERROR: "error",
|
|
RESET: "reset",
|
|
};
|
|
|
|
const initialState = {
|
|
data: [],
|
|
loading: true,
|
|
error: null,
|
|
};
|
|
function reducer(state, action) {
|
|
switch (action.type) {
|
|
case ACTIONS.LOADING:
|
|
return { ...state, loading: true, error: null };
|
|
case ACTIONS.SUCCESS:
|
|
return { ...state, loading: false, data: action.payload };
|
|
case ACTIONS.ERROR:
|
|
return { ...state, loading: false, error: action.payload };
|
|
case ACTIONS.RESET:
|
|
return { ...initialState, loading: false };
|
|
default:
|
|
return state;
|
|
}
|
|
}
|
|
const useCities = (id) => {
|
|
const requestServer = useRequest();
|
|
const [state, dispatch] = useReducer(reducer, initialState);
|
|
|
|
useEffect(() => {
|
|
if (!id) {
|
|
dispatch({ type: ACTIONS.RESET });
|
|
return;
|
|
}
|
|
const fetchCityLists = async () => {
|
|
dispatch({ type: ACTIONS.LOADING });
|
|
try {
|
|
const response = await requestServer(`${GET_CITY_LISTS}/${id}`);
|
|
dispatch({ type: ACTIONS.SUCCESS, payload: response.data.data });
|
|
} catch (error) {
|
|
dispatch({ type: ACTIONS.ERROR, payload: error });
|
|
}
|
|
};
|
|
|
|
fetchCityLists();
|
|
}, [id]);
|
|
|
|
return {
|
|
cityList: state.data,
|
|
loadingCityList: state.loading,
|
|
errorCityList: state.error,
|
|
};
|
|
};
|
|
|
|
export default useCities;
|