Last active
May 31, 2019 11:22
-
-
Save mkontsek/dbfe648e7b8628d4fcc8a9ce64bc8a5b to your computer and use it in GitHub Desktop.
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
import React from 'react'; | |
import { fetchFn } from './myAsyncService' | |
export function cancellableEffect(asyncFunction, afterFunction) { | |
let isCancelled = false; | |
const runAsyncFunction = async () => { | |
const data = await asyncFunction(); | |
if (isCancelled) { | |
return; | |
} | |
afterFunction(data); | |
}; | |
runAsyncFunction(); | |
return () => { | |
isCancelled = true; | |
} | |
} | |
function DynamicItemSelect(props) { | |
const { onChangeItem, fetchFn, name } = props; | |
const [ currentItem, setCurrentItem ] = React.useState(null); | |
const [ items, setItems ] = React.useState(null); | |
const [ loading, setLoading ] = React.useState(true); | |
const updateItem = React.useCallback((item) => { | |
setCurrentItem(item); | |
onChangeItem(item); | |
}, [ setCurrentItem, onChangeItem ]); | |
const cancellableCallback = React.useCallback( | |
() => cancellableEffect( | |
async () => items || await fetchFn(), | |
(result) => { | |
setItems(result); | |
updateItem(result[0]); | |
setLoading(false); | |
}), | |
[ items, fetchFn, updateItem ], | |
); | |
React.useEffect(cancellableCallback); | |
if (loading) { | |
return <h1>Loading {name}(s)...</h1>; | |
} | |
return <h1>{name} {item}</h1>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment