0

I am new to React.js, and I am trying to fetch from an api into a state . But when I do this, after a change in the json code from the api or after some time, I get infinite errors: TypeError: Failed to fetch and Posts.js:10 GET http://localhost:3000/data net::ERR_CONNECTION_REFUSED .

My posts controller:

import React, { useState } from 'react';
import Post from './Post';
import axios from 'axios';


const Posts = () => {
    const [posts, setPosts] = useState([]);


    fetch("http://localhost:3000/data")
    .then(res => res.json())
    .then(
      (result) => {
        setPosts((prev) => prev = result);
      }
    )
    .catch((error) => {
        console.log(error);
      });

    return (
        posts.map((post, index) => (
            <Post name={post.name} content={post.content} key={index}/>
        ))
    );
}
export default Posts;
3
  • 1
    Sounds like an issue with your localhost server Commented Aug 23, 2020 at 3:20
  • But it is normal to get infinite errors ? And in my console for my API I get infinite request while I am on the website Commented Aug 23, 2020 at 3:21
  • 1
    You should also only fetch on initial render - put the fetch inside a useEffect(fn, []) Commented Aug 23, 2020 at 3:22

1 Answer 1

1

First thing you need to wrap api call in function. Otherwise it will re-render every time component renders:

import React, { useState,useEffect } from 'react';
import Post from './Post';
import axios from 'axios';


const Posts = () => {
    const [posts, setPosts] = useState([]);
    
    useEffect(() => {
    fetchPost();
     },[])

    const fetchPost = () => {
        fetch("http://localhost:3000/data")
        .then(res => res.json())
        .then(
        (result) => {
          setPosts((prev) => prev = result);
         }
        )
        .catch((error) => {
         console.log(error);
        });
     }

    return (
        posts.map((post, index) => (
            <Post name={post.name} content={post.content} key={index}/>
        ))
    );
}
export default Posts;

If you need only api when component than pass empty array as dependency. Otherwise variable in which you want to run fetchApi in useEffect([] <- here).

Posts.js:10 GET http://localhost:3000/data net::ERR_CONNECTION_REFUSED

This error generally comes when your backend is not working

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

6 Comments

It works, but what's the point of state if react fetches only one time the data from that api ?
It means like fetching api when component load first time. If its one time data and only update . Not frequent action will change any data so no new fetch is required. if you pass empty array [] in useEffect. It works like componentDidMount of class based. But you passed [variable] in dependency. It kind of work componentDidUpdate where it will run whenever variable value change
Oh I see, so you have to chose if you want only one update or update on change by passing or not that variable ?
Yes correct. If you do not want to call it every time. Pass empty array. If you want to call when certain variable update. Then pass that variable. it will run only for that variable change + first time render
Anytime :-) updated above comment basically if empty array is given in only run first time
|

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.