-
Notifications
You must be signed in to change notification settings - Fork 322
/
Copy pathgameFetch.js
82 lines (76 loc) · 2.26 KB
/
gameFetch.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
import { createSlice } from '@reduxjs/toolkit'
import { batch } from 'react-redux';
const initialState = {
userName: '',
description: '',
actions: [],
loading: false,
coordinates: 'starter-page'
}
export const gameFetch = createSlice({
name: 'gameFetch',
initialState,
reducers: {
setName: (store, action) => {
store.userName = action.payload;
},
setDescription: (store, action) => {
store.description = action.payload;
},
setActions: (store, action) => {
store.actions = action.payload;
},
setCoordinates: (store, action) => {
store.coordinates = action.payload;
},
setLoading: (store, action) => {
store.loading = action.payload;
},
restartGame: () => initialState
}
});
export const fetchOne = () => {
return (dispatch, getState) => {
dispatch(gameFetch.actions.setLoading(true))
setTimeout(() => {
fetch('https://labyrinth.technigo.io/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: getState().gameFetch.userName })
})
.then((res) => res.json())
.then((data) => {
batch(() => {
dispatch(gameFetch.actions.setDescription(data.description));
dispatch(gameFetch.actions.setActions(data.actions));
dispatch(gameFetch.actions.setCoordinates(data.cordinates));
dispatch(gameFetch.actions.setLoading(false));
})
})
}, 1000);
}
}
export const fetchTwo = (direction) => {
return (dispatch, getState) => {
dispatch(gameFetch.actions.setLoading(true));
fetch('https://labyrinth.technigo.io/action', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: getState().gameFetch.userName,
type: 'move',
direction
})
})
.then((res) => res.json())
.then((data) => {
batch(() => {
dispatch(gameFetch.actions.setDescription(data.description));
dispatch(gameFetch.actions.setActions(data.actions));
dispatch(gameFetch.actions.setCoordinates(data.coordinates));
dispatch(gameFetch.actions.setLoading(false));
});
});
};
};
export default gameFetch;