-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCitiesContext.jsx
178 lines (158 loc) · 4.31 KB
/
CitiesContext.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
/* eslint-disable react/prop-types */
import {
createContext,
useCallback,
useContext,
useEffect,
useReducer,
} from "react";
const BASE_URL = "http://localhost:8000";
const CitiesContext = createContext();
const initialState = {
cities: [],
isLoading: false,
currentCity: {},
error: "",
};
function reducer(state, action) {
switch (action.type) {
case "loading":
return { ...state, isLoading: true };
case "cities/loaded":
return {
...state,
isLoading: false,
cities: action.payload,
};
case "city/loaded":
return { ...state, isLoading: false, currentCity: action.payload };
case "city/created":
return {
...state,
isLoading: false,
cities: [...state.cities, action.payload],
currentCity: action.payload,
};
case "city/deleted":
return {
...state,
isLoading: false,
cities: state.cities.filter((city) => city.id !== action.payload),
currentCity: {},
};
case "rejected":
return { ...state, isLoading: false, error: action.payload };
default:
throw new Error("Unknown action type ");
}
}
function CitiesProvider({ children }) {
// const [cities, setCities] = useState([]);
// const [isLoading, setIsLoading] = useState(false);
// const [currentCity, setCurrentCity] = useState({});
const [{ cities, isLoading, currentCity, error }, dispatch] = useReducer(
reducer,
initialState
);
useEffect(function () {
async function fetchCities() {
dispatch({ type: "loading" });
try {
// setIsLoading(true);
const res = await fetch(`${BASE_URL}/cities`);
const data = await res.json();
// setCities(data);
dispatch({ type: "cities/loaded", payload: data });
} catch {
// alert("There was an error fetching the cities");
dispatch({
type: "rejected",
payload: "There was an error loading the cities...",
});
}
}
fetchCities();
}, []);
const getCity = useCallback(
async function getCity(id) {
if (Number(id) === currentCity.id) return;
dispatch({ type: "loading" });
try {
// setIsLoading(true);
const res = await fetch(`${BASE_URL}/cities/${id}`);
const data = await res.json();
// setCurrentCity(data);
dispatch({ type: "city/loaded", payload: data });
} catch {
// alert("There was an error fetching the cities");
dispatch({
type: "rejected",
payload: "There was an error loading the city...",
});
}
},
[currentCity.id]
);
async function createCity(newCity) {
dispatch({ type: "loading" });
try {
// setIsLoading(true);
const res = await fetch(`${BASE_URL}/cities`, {
method: "POST",
body: JSON.stringify(newCity),
headers: {
"Content-Type": "application/json",
},
});
const data = await res.json();
// setCities((cities) => [...cities, data]);
dispatch({ type: "city/created", payload: data });
} catch {
// alert("There was an error fetching the cities");
dispatch({
type: "rejected",
payload: "There was an error creating the city...",
});
}
}
async function deleteCity(id) {
dispatch({ type: "loading" });
try {
// setIsLoading(true);
await fetch(`${BASE_URL}/cities/${id}`, {
method: "DELETE",
});
// setCities((cities) => cities.filter((city) => city.id !== id));
dispatch({ type: "city/deleted", payload: id });
} catch {
// alert("There was an error deleting the cities");
dispatch({
type: "rejected",
payload: "There was an error deleting the city...",
});
}
}
return (
<CitiesContext.Provider
value={{
cities,
isLoading,
currentCity,
error,
getCity,
createCity,
deleteCity,
}}
>
{children}
</CitiesContext.Provider>
);
}
function useCities() {
const context = useContext(CitiesContext);
if (context === undefined)
throw new Error("CitiesContext was used outside of cities provider");
return context;
}
// eslint-disable-next-line react-refresh/only-export-components
export { CitiesProvider, useCities };