I am using react-async to fetch data from api like this:
import {useAsync} from 'react-async'
const getOrders = () => ...
const MyComponent = () => {
const { data, error, isLoading } = useAsync({ promiseFn: getOrders })
if (isLoading) return "Loading..."
if (error) return `Oopsi`
if (data)
return (
<div>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
)
return null
}
Now, how do I update data
(append the next responses to it)?
Should be something like this:
import {useAsync} from 'react-async'
const getOrders = (page) => ...
const MyComponent = () => {
const [page, setPage] = React.useState(1);
const { data, error, isLoading } = useAsync({ promiseFn: getOrders, page: page })
if (isLoading) return "Loading..."
if (error) return `Oopsi`
if (data)
return (
<div>
<pre>{JSON.stringify(data, null, 2)}</pre>
<button onClick={() => {
setPage(page + 1);
getOrders()
}>Get more orders</button>
</div>
)
return null
}
This is currently not built in to React Async. The only way to do it is by keeping your own record of the data (using a separate useState
) and updating that in the onResolve
handler for React Async.
I've setup an example for you here: https://codesandbox.io/s/react-async-pagination-og13b
There's already an issue to track this feature request: https://github.com/async-library/react-async/issues/103