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

Maintaining State Between Calls

Open k-funk opened this issue 5 years ago • 2 comments

First off, thanks for your work this project. Super lightweight and I'm sure is going to simplify my code a lot! 🙇 🙏


Question about default strategy for state inbetween calls

It can be annoying to have the previous async call result be "erased" everytime a new call is triggered (default strategy)

I'm curious why the default strategy was to not maintain previous result state? For nearly all my applications api calls, it looks something like

const [users, setUsers] = useState(undefined)
const [loading, setLoading] = useState(false)

async function getUsers() {
  setLoading(true)
  try {
    // to get behavior like react-async-hook, i'd add a `setUsers(undefined)` here
    const users = await GetUsers()
    setUsers(users)
  } catch (err) {
    setUsers(undefined)
  }
  setLoading(false)
}

What is gained by unsetting the result early? We already know when we are in a loading state so that we can choose to not render the old results if desired.

Improvement suggestions

Design questions aside, I'm wondering if

  1. A descriptively-named option ({ maintainState: true }, { resetResultOnLoading: false }, ...) could be added to do setLoading: state => ({ ...state, loading: true }), because really, I don't want to mess with any loading states, which this appears to do at first glance
  2. It would be great if options (like setLoading) could be more officially documented. I'm proposing using this library to my team, and I know when they see the setLoading option, they're going to be curious about what's happening there, then go to readme, and see it only within a code example.

k-funk avatar Dec 03 '20 22:12 k-funk

Hi,

You are right that maintaining the previous state should be the default behavior, and will likely change it and document it better for a version2 with some breaking changes like this.

slorber avatar Dec 07 '20 16:12 slorber

🙏

If you have intentions of publishing a beta before a v2, let me know here in case there are other enhancements that you have planned and need someone to test out those changes in their working application..

k-funk avatar Dec 07 '20 16:12 k-funk