admin管理员组

文章数量:1415139

This question relates a lot with loading and fetching. So I have this react ponents that loads ments from an API

function App (){

    const [, setCom] = useState([])

    const [isLoading, setLoading] = useState(true)


    useEffect(() =>{

        fetch('').then(ddd => ddd.json())
        .then(data => {


             setCom(data)

            setLoading(false)
        })
    })
    
    const s = .map(data => <h3>{data.body} <br/></h3>)

    if(isLoading){

        return <h1>Loading</h1>
    }
    else if(isLoading === false){
        return (

            <div className="con">
                {s}
            </div>
        )
    }
}

so in this ponents I have two states one to store the ments and other to store a loading value that will change after it's done fetching the state in the useEffect.

The problem with this code is that let's say the server went down or my internet went out, even if it es back this ponent is going to stay in the loading phase forever until the user refreshes the page manually. So how do I make the ponents re-fetch the data or rather just refresh the ponents ?.

Thank you in advance

This question relates a lot with loading and fetching. So I have this react ponents that loads ments from an API

function App (){

    const [, setCom] = useState([])

    const [isLoading, setLoading] = useState(true)


    useEffect(() =>{

        fetch('https://jsonplaceholder.typicode./ments?postId=5').then(ddd => ddd.json())
        .then(data => {


             setCom(data)

            setLoading(false)
        })
    })
    
    const s = .map(data => <h3>{data.body} <br/></h3>)

    if(isLoading){

        return <h1>Loading</h1>
    }
    else if(isLoading === false){
        return (

            <div className="con">
                {s}
            </div>
        )
    }
}

so in this ponents I have two states one to store the ments and other to store a loading value that will change after it's done fetching the state in the useEffect.

The problem with this code is that let's say the server went down or my internet went out, even if it es back this ponent is going to stay in the loading phase forever until the user refreshes the page manually. So how do I make the ponents re-fetch the data or rather just refresh the ponents ?.

Thank you in advance

Share Improve this question asked Apr 30, 2021 at 16:39 MellyMelly 75510 silver badges31 bronze badges 2
  • swr.vercel.app solves the issue, without you writing a bunch of logic. The package is designed exactly for your use case. – thevarunraja Commented Apr 30, 2021 at 16:46
  • You could put setLoading in a finally block instead of the then block... fetch().then(setCom).finally(() => setLoading(false)) – Tom Commented Apr 30, 2021 at 16:48
Add a ment  | 

2 Answers 2

Reset to default 3

Here are a few improvements on how you can handle above logic.

    function App() {
      const [, setCom] = useState([]);
      const [isLoading, setisLoading] = useState(false); //Set initial value to false to avoid your ponent in loading state if the first call fails
      const refreshTime = 2000 //How frequently you want to refresh the data, in ms
      
      const fetchComments = async () => {
        setisLoading(true) //set to true only when the api call is going to happen
        const data = await fetch('https://jsonplaceholder.typicode./ments?postId=5').then(ddd => ddd.json()).then(data => {
          if(Array.isArray(data)) setCom(data);
        })
        setisLoading(false); //make sure to set it to false so the ponent is not in constant loading state
      }
      
      useEffect(() => {
        const Interval = setInterval(fetchComments, refreshTime); //This will refresh the data at regularIntervals of refreshTime
        return () => clearInterval(Interval) //Clear interval on ponent unmount to avoid memory leak
      },[])
      
      const s = .map(data => <h3>{data.body} <br/></h3>)
      if(isLoading){

            return <h1>Loading</h1>
        }
        else if(isLoading === false){
            return (

                <div className="con">
                    {s}
                </div>
            )
        }
    }

You could just use setInterval() to update the state with fetched data every second or however long is required. Here is an example:

const [fetchedData, setFetchedData] = useState(/* data type */);
setInterval(() => setFetchedData(/* call to the method */), 1000);

This way, the ponent will fetch data every second and re-render the ponent.

Keep in mind though, this should ONLY be used if you know you are going to get an update every so often. If you are uselessly re-rendering and re-fetching data, that will be a constant hinderance towards performance.

本文标签: javascriptHow do you constantly refresh a react component every certain amount of timeStack Overflow