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 ?

2
  • Please provide a producible example How to create a Minimal, Reproducible Example. Commented Nov 15, 2019 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 Commented Nov 15, 2019 at 13:51

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.