Skip to content

Instantly share code, notes, and snippets.

@mkontsek
Last active May 31, 2019 11:22
Show Gist options
  • Save mkontsek/dbfe648e7b8628d4fcc8a9ce64bc8a5b to your computer and use it in GitHub Desktop.
Save mkontsek/dbfe648e7b8628d4fcc8a9ce64bc8a5b to your computer and use it in GitHub Desktop.
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