async-library / react-async

🍾 Flexible promise-based React data loader

Home Page:https://docs.react-async.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

OnResolve is called after if(data)

nikhrasatyam opened this issue · comments

First of all thanks for developing this library. I just started using this and got stuck with this one.

Is there any way to call onResolve first and then if(data) condition without doing something hacky?

import { useAsync } from "react-async"
const [response,setResponse] = React.useState(null);

const updateResponse = (response)=>{
//do some calculation with response
setResponse(response);
}

const loadPlayer = async ({ playerId }, { signal }) => {
  const res = await fetch(`/api/players/${playerId}`, { signal })
  if (!res.ok) throw new Error(res.statusText)
  return res.json()
}

const MyComponent = () => {
  const { data, error, isPending } = useAsync({ promiseFn: loadPlayer, playerId: 1, onResolve: updateResponse})
  if (isPending) return "Loading..."
  if (error) return `Something went wrong: ${error.message}`
  if (data) // I want to call this after updateResponse is called
    return (
      <div>
        <strong>Player data:</strong>
        <pre>{JSON.stringify(data, null, 2)}</pre>
      </div>
    )

// I am avoiding using something like this 
  if (response) 
    return (
      <div>
        <strong>Player data:</strong>
        <pre>{JSON.stringify(data, null, 2)}</pre>
      </div>
    )
  return null
}

Why don't you just do your calculation in loadPlayer?

Thanks for the quick reply actually in my project I am directly pulling the API promise function call from different files and injecting into react-async. So In my scenario, this loadPlayer function is a part of different file as it can be utilized by different components. Is there any way I can achieve this without introducing a middleware function between loadPlayer and useAsync?

In that case I recommend creating a wrapper function for loadPlayer and use that as your promiseFn (maybe just call it that). Call it middleware if you want. This is by far the simplest approach, as it remains vanilla JavaScript. There is no "preResolve" option in React Async.

gotcha. Thanks