Home > Software design >  How to display fetch data only when is required
How to display fetch data only when is required

Time:04-13

I'm new with ReactJs and I need a little help. (useEffect -> Axios.Get) constantly is making requests to the API. I thought post data should be set in setPosts(res.data) and later those posts are displayed. How can I fix this issue?

export function FetchPosts(){

    const [posts, setPosts] = useState([]);
  

    function AddFire(id){
        fetch(`https://localhost:7187/api/Post/${id}`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            }
        }).then(res => console.log(res)).catch(err => {alert(err)})

        document.querySelector(`.postId-${id}`).src = onFire; 
    }

    useEffect(()=>{
        //Posts
        Axios.get(`${apiUrl}/api/Post`)
        .then(res => {setPosts(res.data)})
        .catch(err => console.log(err))
    })  

    return(
        <div id="all-posts">
                <h3>ALL POSTS ARE HERE</h3>
                <div className="all-posts-container">
                    {posts.map((post)=>{
                        return(
                            <li key={post.id} className="fire-content">
                                <span>{post.text}</span>
                                <div className="fire-container">
                                    <img onClick={() => AddFire(post.id)} src={imgFire} className={`post-fire postId-${post.id}`} alt="post-fire"/>
                                    <span className="fire-font">{post.fires}</span>
                                </div>
                            </li>
                        )
                    })}
                </div>
        </div>
    )
}

CodePudding user response:

When no dependency array at all is passed to useEffect then it executes on every render. If, as in this case, the operation within useEffect changes state and triggers a re-render, clearly this becomes problematic.

Alternatively, if you pass an empty dependency array, it only executes on the first render:

useEffect(()=>{
    //Posts
    Axios.get(`${apiUrl}/api/Post`)
    .then(res => {setPosts(res.data)})
    .catch(err => console.log(err))
}, []); // <---- here
  • Related