react-async-hook icon indicating copy to clipboard operation
react-async-hook copied to clipboard

Consider adding an option "onLoad"?

Open freewind opened this issue 4 years ago • 3 comments

I see there are some options like onSuccess, onError which allow us to do something that has side-effects, but no one likeonLoad when the fetching is started.

It might be useful if we want to reset something e.g. selected value of a dropdown, before we fetching new options.

I tried several solutions:

  1. do it in the fetching function:
const fetchOptions = useAsync(async () => {
  store.selectedValue = null;
  return await fetchOptionsFromRemote();
}, [])
  1. use another useEffect:
const fetchOptions = useAsync(async () => {
  return await fetchOptionsFromRemote();
}, [])

useEffect(() => {
  if(fetchOptions.loading) {
    store.selectedValue = null;
  }
}, [fetchOptions.loading]);

But neither looks as great as we can just:

const fetchOptions = useAsync(async () => {
  return await fetchOptionsFromRemote();
}, [], {
  onLoad: () => {  store.selectedValue = null }
})

freewind avatar Jan 11 '21 13:01 freewind

const { execute } = useAsyncCallback(fetchOptionsFromRemote);

const fetchOptions = useCallback(execute,[]);
useEffect(() => {
  fetchOptions().then(() => {
    store.selectedValue = null;
  });
}, [fetchOptions]);

or use setResult in option?

pig800509 avatar Feb 18 '21 03:02 pig800509

@pig800509 If I understand correctly, your solution looks like doing something after loading (there is already an onSucess for this). I want to do something before loading started.

freewind avatar Feb 20 '21 14:02 freewind

@freewind

const fetchOptions = useAsync(async () => {
  store.selectedValue = null;  //do something here.
  return await fetchOptionsFromRemote();
}, [])

What is different with "onLoad" options?

pig800509 avatar Dec 17 '21 07:12 pig800509