-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStore.js
77 lines (62 loc) · 1.92 KB
/
Store.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
import { observable, action, computed } from 'mobx';
import fetch from 'better-fetch';
import { PORTRAIT, CLIENT_ID } from './Constants';
const IMGUR_URL = 'https://api.imgur.com/3/';
fetch.setDefaultHeaders({
Authorization: `Client-ID ${CLIENT_ID}`
});
class Store {
@observable orientation = PORTRAIT;
@observable images = [];
@observable index = 0;
@observable galleryPage = 0;
@observable albums = new observable.map();
@observable screenSize = {
width: null,
height: null
};
@action changeOrientation(orientation) {
this.orientation = orientation;
}
@action updateScreenSize(width, height) {
this.screenSize.width = width;
this.screenSize.height = height;
}
@action prevImage() {
this.index = this.index - 1;
if (this.index < 1) {
this.index = 0;
}
}
@action nextImage() {
this.index = this.index + 1;
if (this.index > this.images.length) {
this.galleryPage = this.galleryPage+1;
this.fetchImages();
}
}
@action fetchImages() {
fetch(`${IMGUR_URL}gallery/hot/viral/${this.galleryPage}`)
.then(fetch.throwErrors)
.then(res => res.json())
.then(json => {
json.data.forEach(img => this.images.push(img));
})
.catch(err => console.log('ERROR', err.message));
}
@action fetchAlbum(id) {
if (!this.albums.has(id)) {
fetch(`${IMGUR_URL}album/${id}`)
.then(fetch.throwErrors)
.then(res => res.json())
.then(json => {
this.albums.set(json.data.id, json.data);
})
.catch(err => console.log('ERROR', err.message, err));
}
}
@computed get currentImage() {
return this.images.length ? this.images[this.index] : null;
}
}
export default new Store();