-
Notifications
You must be signed in to change notification settings - Fork 0
/
HolidaysContext.js
207 lines (193 loc) · 6.31 KB
/
HolidaysContext.js
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import React, {
useState,
createContext,
useEffect,
useContext,
useRef
} from "react";
import axios from "axios";
import DateContext from "../2-context/DateContext";
import AuthContext from "../2-context/AuthContext";
const HolidaysContext = createContext();
export const HolidaysContextProvider = props => {
const [countryObj, setCountryObj] = useState();
const [showHolidays, setShowHolidays] = useState();
const [holidays, setHolidays] = useState(null);
const [storedHolidays, setStoredHolidays] = useState(null);
const [supportedCountries, setSupportedCountries] = useState([]);
const { dateObj } = useContext(DateContext);
const { authenticated } = useContext(AuthContext);
//needed for comparison to check whether user has changed year (in which case holidays must be fetched) or just month (see #7)
const usePrevious = value => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
const prevDateObj = usePrevious(dateObj);
useEffect(() => {
if (authenticated) {
getSupportedCountries();
getInitialHolidaysPref();
}
//eslint-disable-next-line
}, [authenticated]);
//1. Check LS if already saved there and, if so, save to state, else make API call to get list and save to state
const getSupportedCountries = () => {
const savedSupportedCountries = JSON.parse(
localStorage.getItem("supportedCountries")
);
if (savedSupportedCountries) {
setSupportedCountries(savedSupportedCountries);
} else {
axios
.get("/api/supportedCountries", { timeout: 5000 })
.then(res => {
setSupportedCountries(res.data);
localStorage.setItem("supportedCountries", JSON.stringify(res.data));
})
.catch(err => {
console.log(err);
});
}
};
//2. Check LS for saved preference and save to state, else set to default ('Show')
const getInitialHolidaysPref = () => {
const savedHolidaysPref = JSON.parse(localStorage.getItem("holidaysPref"));
if (savedHolidaysPref) {
setShowHolidays(savedHolidaysPref);
} else {
setShowHolidays("Show");
}
};
//3. If holidays preference changes, save new preference to LS. If 'Hide', set holidays to empty array. Else check LS for saved country and save to state
//If no location in LS, get location from setLocation()
useEffect(() => {
if (showHolidays) {
localStorage.setItem("holidaysPref", JSON.stringify(showHolidays));
if (showHolidays === "Hide") {
setHolidays([]);
return;
} else {
const savedLocation = JSON.parse(localStorage.getItem("country"));
if (!savedLocation) {
setLocation();
} else {
setCountryObj({ name: savedLocation.name, code: savedLocation.code });
}
}
}
}, [showHolidays]);
//4. Try to get user's GPS coordinates. If permission given, make API call to get country info from coordinates and set. Else set default (UK)
const setLocation = () => {
navigator.geolocation.getCurrentPosition(
pos => {
const latitude = pos.coords.latitude;
const longitude = pos.coords.longitude;
axios
.post("/api/countryInfo", { latitude, longitude }, { timeout: 5000 })
.then(res => {
setCountryObj({
name: res.data.countryName,
code: res.data.countryCode
});
})
.catch(err => {
console.log(err);
});
},
() => {
setCountryObj({ name: "United Kingdom", code: "GB" });
},
{ timeout: 5000 }
);
};
//5. When countryObj changes, save to LS. Before making API call, check both state and LS for that country's holidays. If not there, call fetchHolidays().
useEffect(() => {
if (countryObj && countryObj.code) {
localStorage.setItem("country", JSON.stringify(countryObj));
if (
storedHolidays &&
storedHolidays.holidays.length > 0 &&
storedHolidays.code === countryObj.code &&
storedHolidays.year === dateObj.year
) {
setHolidays(storedHolidays.holidays);
return;
}
const savedHolidays = JSON.parse(localStorage.getItem("holidays"));
if (
savedHolidays &&
savedHolidays.code === countryObj.code &&
savedHolidays.year === dateObj.year
) {
setHolidays(savedHolidays.holidays);
setStoredHolidays(savedHolidays);
return;
}
fetchHolidays();
}
//eslint-disable-next-line
}, [countryObj]);
//6. Make API call for holidays using year and country
const fetchHolidays = () => {
if (countryObj && countryObj.code && dateObj.year) {
axios
.post(
"/api/holidays",
{ country: countryObj.code, year: dateObj.year },
{ timeout: 5000 }
)
.then(res => {
//this variable used to populate calendar
setHolidays(res.data);
//another copy saved in this variable in case user toggles holidays (no need to call API again)
setStoredHolidays({
code: countryObj.code,
year: dateObj.year,
holidays: res.data
});
// setHolidaysYear(dateObj.year);
localStorage.setItem(
"holidays",
JSON.stringify({
code: countryObj.code,
year: dateObj.year,
holidays: res.data
})
);
})
.catch(err => {
console.log(err);
});
}
};
useEffect(() => {
//7. if user changes date while using calendar, fetch holidays from API if they changed the year
if (
dateObj &&
countryObj &&
prevDateObj &&
dateObj.year !== prevDateObj.year
) {
fetchHolidays();
}
//eslint-disable-next-line
}, [dateObj]);
return (
<HolidaysContext.Provider
value={{
showHolidays,
setShowHolidays,
holidays,
countryObj,
setCountryObj,
supportedCountries
}}
>
{props.children}
</HolidaysContext.Provider>
);
};
export default HolidaysContext;