UNPKG

orb-ui-firebase

Version:

Firebase with redux

88 lines (72 loc) 2.38 kB
import * as types from './types'; import * as selectors from './selectors'; import * as initSelectors from '../initialization/selectors'; import { logError } from '../errors/actions'; import { logLoading } from '../loadings/actions'; export var valueChanged = function valueChanged(value, location, path) { return { type: types.VALUE_CHANGED, payload: value, path: path, location: location, locationValue: true }; }; export var destroy = function destroy(location) { return { type: types.DESTROY, location: location }; }; export var unWatch = function unWatch(path) { return { type: types.UNWATCH, path: path }; }; export function watchPath(firebaseApp, firebasePath) { var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var logLoad = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; var location = reduxPath || firebasePath; return function (dispatch, getState) { var isInitialized = initSelectors.isInitialised(getState(), location); if (!isInitialized) { var ref = firebaseApp.database().ref(firebasePath); var path = ref.toString(); if (logLoad) { dispatch(logLoading(location)); } ref.on('value', function (snapshot) { dispatch(valueChanged(snapshot.val(), location, path)); }, function (err) { dispatch(logError(location, err)); }); } }; } export function unwatchPath(firebaseApp, path) { var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; return function (dispatch) { var location = reduxPath || path; firebaseApp.database().ref(path).off(); dispatch(unWatch(location)); }; } export function destroyPath(firebaseApp, path) { var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var location = reduxPath || path; return function (dispatch) { firebaseApp.database().ref(path).off(); dispatch(unWatch(location)); dispatch(destroy(location)); }; } export function unwatchAllPaths(firebaseApp) { return function (dispatch, getState) { var allPaths = selectors.getAllPaths(getState()); Object.keys(allPaths).forEach(function (key, index) { firebaseApp.database().ref(allPaths[index]).off(); dispatch(unWatch(key)); }); }; }