aboutsummaryrefslogtreecommitdiffstats
path: root/web/src/js/ducks/options.js
blob: 06144a3c3ee293c353e02a2ec7e5ddd5f8fe53dd (plain)
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
import { fetchApi } from "../utils"
import * as optionsEditorActions from "./ui/optionsEditor"
import _ from "lodash"

export const RECEIVE = 'OPTIONS_RECEIVE'
export const UPDATE = 'OPTIONS_UPDATE'
export const REQUEST_UPDATE = 'REQUEST_UPDATE'

const defaultState = {}

export default function reducer(state = defaultState, action) {
    switch (action.type) {

        case RECEIVE:
            return action.data

        case UPDATE:
            return {
                ...state,
                ...action.data,
            }

        default:
            return state
    }
}

export function pureSendUpdate (option, value, dispatch) {
    fetchApi.put('/options', { [option]: value }).then(response => {
        if (response.status === 200) {
            dispatch(optionsEditorActions.updateSuccess(option))
        } else {
            response.text().then(error => {
                dispatch(optionsEditorActions.updateError(option, error))
            })
        }
    })
}
let sendUpdate = _.throttle(pureSendUpdate, 700, { leading: true, trailing: true })

export function update(option, value) {
    return dispatch => {
        dispatch(optionsEditorActions.startUpdate(option, value))
        sendUpdate(option, value, dispatch);
    }
}