forked from WebMemex/webmemex-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions.js
48 lines (38 loc) · 1.78 KB
/
actions.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
import { createAction } from 'redux-act'
import { onDatabaseChange } from '../pouchdb'
import { filterVisitsByQuery } from '../search'
import { ourState } from './selectors'
// == Simple commands to change the state in reducers ==
export const setQuery = createAction('overview/setQuery')
export const setSearchResult = createAction('overview/setSearchResult')
// == Actions that trigger other actions ==
// Initialisation
export function init() {
return function (dispatch, getState) {
// Perform an initial search to populate the view (empty query = get all docs)
dispatch(refreshSearch())
// Track database changes, to e.g. trigger search result refresh
onDatabaseChange(change => dispatch(handlePouchChange({change})))
}
}
// Search for docs matching the current query, update the results
export function refreshSearch() {
return function (dispatch, getState) {
const query = ourState(getState()).query
const oldResult = ourState(getState()).searchResult
filterVisitsByQuery({query}).then(searchResult => {
// First check if the query and result changed in the meantime.
if (ourState(getState()).query !== query
&& ourState(getState()).searchResult !== oldResult) {
// The query already changed while we were searching, and the
// currently displayed result may already be more recent than
// ours. So we did all that effort for nothing.
return
}
// Set the result to have it displayed to the user.
dispatch(setSearchResult({searchResult}))
})
}
}
// Report a change in the database, to e.g. trigger a search refresh
export const handlePouchChange = createAction('overview/handlePouchChange')