bookingActions.js
2.72 KB
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
import axios from "axios";
import { BOOKING_DETAILS_SUCCESS, BOOKING_DETAILS_FAIL, FETCH_MY_BOOKINGS_SUCCESS, FETCH_MY_BOOKINGS_FAIL, CLEAR_ERRORS } from "../constants/bookingConstants";
import qs from "qs";
// Fetch room booked dates.
export const fetchMyBookings = session => async dispatch => {
// Note, when an action is going to be triggered on the server side, like this one is.
// then we cannot expect getSession() to give usa valid session, we need to instead use getSession({ req })
// and give it a req object instead.
// This action gets called from getServerSideProps on the me.js file.
// Hence here we have taken the session object from outside, instead of using getSession().
// Unlike a few other actions where we might have ended up using getSession directly, those actions like the loadUser & updateUser actions
// are all triggered on the UI using useEffect and from a submitHandler respectively.
if (!session) {
throw new Error("You are not authenticated currently. Only authenticated users can fetch their own bookings.");
}
try {
const config = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session.jwt}`
}
};
const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/my-bookings`, config);
dispatch({
type: FETCH_MY_BOOKINGS_SUCCESS,
payload: response.data.bookings
});
} catch (error) {
dispatch({
type: FETCH_MY_BOOKINGS_FAIL,
payload: error.response.data
});
}
};
// Get room details
export const getBookingDetails = (bookingId, session) => async dispatch => {
// const session = await getSession();
if (!session) {
throw new Error("You are not authenticated currently. Only authenticated users can fetch their own bookings.");
}
try {
const config = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session.jwt}`
}
};
const query = qs.stringify(
{
populate: {
room: {
populate: ["images"]
},
user: {
populate: ["*"]
}
}
},
{
encodeValuesOnly: true // prettify URL
}
);
const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/bookings/${bookingId}?${query}`, config);
dispatch({
type: BOOKING_DETAILS_SUCCESS,
payload: response.data
});
} catch (error) {
console.log("getBookingDetails:");
console.log(error.response.data);
dispatch({
type: BOOKING_DETAILS_FAIL,
payload: error.response.data
});
}
};
// Clear errors
export const clearErrors = () => async dispatch => {
dispatch({
type: CLEAR_ERRORS
});
};