-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathgiphy.js
70 lines (63 loc) · 1.69 KB
/
giphy.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
/*
init : () -> state
update : (state, action) -> state
effects : (dispatch, state) -> {html, http}
*/
// import Type from 'union-type'
import curry from 'ramda/src/curry'
import merge from 'ramda/src/merge'
import h from 'react-hyperscript'
const loadingGif = require('tutorial/loading.gif')
const errorGif = require("tutorial/error.gif")
const randomUrl = (topic) =>
"http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=#{topic}"
// init : () -> state
const init = (topic="explosions") => {
return { topic: topic, url: loadingGif, count: 0, pending: true}
}
// update : (dispatch, state, action) -> state
const update = curry((state, action) => {
switch (action.type) {
case 'newGif':
return merge(state, {
url: action.url,
pending: false
})
case 'errorGif':
return merge(state, {
url: errorGif,
pending: false
})
case 'anotherGif':
return merge(state, {
url: loadingGif,
count: state.count + 1,
pending: true
})
default:
return state
}
})
let view = curry((dispatch, state) => {
return {
html:
h('div.giphy', [
h('h2.topic', state.topic),
h('img', {src: state.url}),
h('button', {
onClick: () => dispatch({type: 'anotherGif'})
}, 'Gimme More!')
]),
http: !state.pending ? [] :
[{
key: state.count,
url: randomUrl(state.topic),
method: 'get',
onSuccess: (response) =>
dispatch({type: 'newGif', url: response.json.data.image_url}),
onError: (response) =>
dispatch({type: 'errorGif', error: error})
}]
}
})
export default {init, view, update}