2

I am using useEffect, useState and fetch. On page load i got a list of project ids. then i am calling api on base of those ids. In this way my application get slow down and their is chance to lose data sometime. I am looking for a optimize way resolve this. Any Suggestion ?

User99
  • 129
  • 1
  • 11
  • Please provide a producible example [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – Dennis Vash Nov 15 '19 at 13:50
  • You'd probably want to improve your api, so that you can do one call all data related to these id's – Jurrian Nov 15 '19 at 13:51

2 Answers2

0

Just use promise to chain your api calls without lost any data. Or if you can, edit your API to get projects ID and data with just one call.

See https://stackoverflow.com/a/40981298/9811156

Robilol
  • 146
  • 1
  • 6
0

You can out source them and use them as hooks if they are supposed to be used in multiple places

eg:


import { usePosts } from '../hooks'

const Comp = () => {
  //                                         according to need
  const { loading: pLoading, error: pError, posts } = usePosts({ limit: 10, offset: 0 })
  // same for others
  const { loading: cLoading, error: cError, comments } = useComments(postId)

  return (
    ...someMagicStuff
  )
}

export default Comp

hooks:

const usePosts = ({ limit, offset }) => {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(false)
  const [posts, setPosts] = useState([])

  useEffect(() => {
    setLoading(true)
    // use limit offset variables
    fetch(url)
      .then(res => res.json())
      .then(posts => {
         setPosts(posts)
         setLoading(false)  
       })
       .catch(error => setError(true))
  })

  return {loading, error, posts}

}
Dev K
  • 35
  • 6