Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display fetch data only when is required

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>
    )
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading