2

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!

DoneDeal0
  • 5,273
  • 13
  • 55
  • 114

3 Answers3

3

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

0

Try something like this:

// fetch data 
function fetchSomeData(baseCatUrl) {
  let status = "pending";
  let result;
  let suspender = axios(baseCatUrl).then((res) => {
    status = "success";
    result = res.data;
  }, (e) => {
    status = "error";
    result = e;
  });
  return {
    read() {
      if (status === "pending") {
        throw suspender;
      } else if (status === "error") {
        throw result;
      }
      else if (status === "success") {
        return result;
      }
    }
  }
}

// Component using data 
const resource = fetchSomeData(baseCatUrl);
const Component = () => {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <ChildComponent resource={resource} />
    </Suspense>
  )
};
Liki Crus
  • 1,901
  • 5
  • 16
  • 27
-6

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

Tan Kim Loong
  • 980
  • 7
  • 14