Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use React.Suspense with a api call?

I've read the doc about React.Suspense, it seems great, but how can I use it while performing an api call, with axios for example?

To be more specific, why this code doesn't work?

export default function Foo(){
const [state, setState] = useState()

useEffect(()=> {
    axios.get("url")
    .then(res=> setState(res.data))
    .catch(_=> setState(null)
}, [])

return (
    <Suspense fallback="loading data">
       <div>hello {state.name}</div>
    </Suspense>
)
}

Thanks!

like image 893
DoneDeal0 Avatar asked Nov 30 '25 17:11

DoneDeal0


1 Answers

According to the React documentation, what you are trying to achieve is possible. There is an experimental feature called Concurrent Mode. You can find the implementation details in React documentation. Link to the Suspense documentation: https://reactjs.org/docs/concurrent-mode-suspense.html

But there is a limitation, you have to use an npm package which leverages this feature. Relay is what is suggested by the React team.

This is the code sandbox link provided in the documentation itself.

https://codesandbox.io/s/frosty-hermann-bztrp

like image 51
Prajwal V Bharadwaj Avatar answered Dec 02 '25 13:12

Prajwal V Bharadwaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!