Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

watch behavior differing from useEffect can be confusing #254

Open
loganyott opened this issue Feb 7, 2020 · 2 comments
Open

watch behavior differing from useEffect can be confusing #254

loganyott opened this issue Feb 7, 2020 · 2 comments
Labels
enhancement Enhancement to existing feature

Comments

@loganyott
Copy link

useEffect is a common way to load async data right now in React. useEffect supports watching specific dependencies.

const [value, setValue] = useState();

useEffect(() => {
  setData(myFetchFn({ value });
  return cancel;
}, [value]);

Now if I update value, I automatically get updated data.

react-async supports something similar

const [value, setValue] = useState();

const { data } = useAsync({ promiseFn: myFetchFn, value, watch: value })

However, when I first did this, I expected watch to follow useEffect's syntax of passing an array of dependencies rather than it watching the primitive value. ex: watch: [value]

It would be great if react-async treated an array being passed in to watch similar to the dependency array in useEffect as it's a little confusing coming from useEffect why passing an array causes an infinite render loop.

@Ciccio99
Copy link

I second this. The current way also prevents you from watching multiple values.

@ghengeveld
Copy link
Member

ghengeveld commented Aug 22, 2020

This would be a breaking change, but I can get behind adding special handling for arrays. Feel free to open a PR. For now, you can achieve what you want using watchFn:

useAsync({
  deps: [...],
  watchFn: (props, prevProps) => JSON.stringify(props.deps) === JSON.stringify(prevProps.deps)
})

There's better/faster ways to compare two arrays, but this is the simplest way.

In fact you can use the stringify trick with watch itself:

useAsync({
  watch: JSON.stringify([ ... ])
})

@ghengeveld ghengeveld added the enhancement Enhancement to existing feature label Dec 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Enhancement to existing feature
Projects
None yet
Development

No branches or pull requests

3 participants