1

I'm trying to automatically update a table - In my testing I log the output every 10 seconds however the response stays the same from the initial component render

componentDidMount() {       
    this.interval = setInterval(this.getData, 10000);
    this.getData()        
}

getData = () => {
    axios.get(`myApiUrl`)
        .then(response => {
            this.setState({ data: response.data.entries })
            console.log(response.data.entries)
        })
        .catch(error => {
            console.log(error)
        })
}

componentWillUnmount() {
    clearInterval(this.interval)
}

If I manually try to grab the data from postman every 10 seconds, the updated changes works fine.

buzz
  • 171
  • 1
  • 3
  • 13
  • 1
    What is the "change" you're expecting every 10 seconds? It looks like you're just making the exact same API request over and over, so results aren't gonna be different – Jayce444 Jan 30 '22 at 22:42
  • The data is being updated from another source - I would like to see these changes reflected every 10 seconds. @Jayce444 – buzz Jan 30 '22 at 22:45
  • 2
    your browser is probably caching the data, since the request hasn't changed. If you control the server for the API you might need to send the right response headers to ensure the browser doesn't cache it. – Robin Zigmond Jan 30 '22 at 22:46
  • This is probably what you need (useEffect hook): https://stackoverflow.com/questions/57542264/how-to-setinterval-for-every-5-second-render-with-react-hook-useeffect-in-react – Louys Patrice Bessette Jan 30 '22 at 23:05
  • @RobinZigmond correct! – buzz Jan 30 '22 at 23:19

1 Answers1

1

@Robin Zigmond was correct

Updated the call to remove the cache

getData = () => {
        axios.get(`myApiUrl`, {
            headers: {
                'Cache-Control': 'no-cache',                
            }
        })
            .then(response => {
                this.setState({ data: response.data.entries })
                console.log(response.data.entries)
            })
            .catch(error => {
                console.log(error)
            })
    }
buzz
  • 171
  • 1
  • 3
  • 13