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 ?
-
Please provide a producible example How to create a Minimal, Reproducible Example.Dennis Vash– Dennis Vash2019-11-15 13:50:11 +00:00Commented 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'sJurrian– Jurrian2019-11-15 13:51:55 +00:00Commented Nov 15, 2019 at 13:51
Add a comment
|
2 Answers
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.
Comments
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}
}