Home > Blockchain >  Updating state based on changing API React
Updating state based on changing API React

Time:07-08

Is it possible to have an api constantly being called (in a loop until asked to stop) or have react automatically change state if the api changes?

I currently have a backend (/logs) that will send out logs in an array ex: [{log:"test"}, {log:"test1"}].

I have react able to pick that up and update state to display those logs on the front end when a button is clicked

axios.get("/logs").then(response =>{
    let templog = response.data
    let newLogs = [...logs]
    for (let i = 0; i < templog.length; i  ) {
        if (templog[i].log !== "") {
            newLogs.push({log: templog[i].log, id: uuidv4()})
        }
    }
    setLogs(newLogs)
})

Right now, if I update the backend, I would have to reclick the button for the state to update rather than the state automatically updating based on the api

CodePudding user response:

try setInterval in useEffect, also return clearInterval at end of useEffect

import React from 'react'

const ScheduleUpdate = (props) => {
    const [logs, setLogs] = React.useState([])
    const [run, setRun] = React.useState(true)

    React.useEffect(() => {
        const getLogs = () => {
            fetch("/logs")
            .then(r => r.json())
            .then(d => { setLogs(d) })
        }

        if (run){
            const handle = setInterval(getLogs, 1000);

            return () => clearInterval(handle);
        }
    }, [run])
   return (
       <div>
           <h1>ScheduleUpdate</h1>
           {
                logs.map(l => <div>{l}</div>)
           }
           <button onClick={() => setRun(false)}>Stop</button>
       </div>
   )
}

export default ScheduleUpdate

  • Related