PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 12, 2022

[FIXED] How to use React.Suspense with a api call?

 October 12, 2022     axios, react-suspense, reactjs     No comments   

Issue

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!


Solution

Suspense is used to asynchronously load Components, not APIs. It's used to lazily load components imported using React.lazy.

Even if you manage to render your component it'll not make any difference in your case. You'll need it for a different use case



Answered By - Tan Kim Loong
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing