forked from zotero/zoterobib
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Simplify state with useReducer() in container
- Loading branch information
Showing
6 changed files
with
201 additions
and
146 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import { CONFIRM_CURRENT_STYLE, REQUEST_FETCH_STYLE, RECEIVE_FETCH_STYLE, ERROR_FETCH_STYLE, | ||
SELECT_CURRENT_STYLE } from './constants/actions'; | ||
import { fetchWithCachedFallback } from './utils'; | ||
import { getStyleProperties } from './get-style-properties'; | ||
|
||
const stylesCache = new Map(); | ||
|
||
const fetchAndSelectStyle = async (dispatch, styleName, opts = {}) => { | ||
dispatch({ type: REQUEST_FETCH_STYLE, styleName }); | ||
let nextStyleName = styleName, styleXml, styleProps; | ||
|
||
do { | ||
if(stylesCache.has(styleName)) { | ||
styleXml = stylesCache.get(styleName); | ||
} else { | ||
const url = `https://www.zotero.org/styles/${styleName}`; | ||
try { | ||
const response = await fetchWithCachedFallback(url); | ||
if(!response.ok) { | ||
throw new Error(`Failed to fetch ${styleName} from ${url}`); | ||
} | ||
styleXml = await response.text(); | ||
} catch(error) { | ||
dispatch({ type: ERROR_FETCH_STYLE, styleName, error }); | ||
throw error; | ||
} | ||
stylesCache.set(styleName, styleXml); | ||
} | ||
styleProps = getStyleProperties(styleXml); | ||
const { parentStyleName } = styleProps | ||
nextStyleName = parentStyleName; | ||
} while(nextStyleName); | ||
|
||
dispatch({ | ||
type: RECEIVE_FETCH_STYLE, styleName, styleXml, styleProps, ...opts | ||
}); | ||
|
||
dispatch({ | ||
type: SELECT_CURRENT_STYLE, styleName, styleXml, styleProps, ...opts | ||
}); | ||
} | ||
|
||
const confirmStyle = dispatch => dispatch({ type: CONFIRM_CURRENT_STYLE }); | ||
|
||
export { confirmStyle, fetchAndSelectStyle }; |
Oops, something went wrong.