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 set state from an Axios get request without causing a re-render

I am fairly new to React. I am currently having the problem that I am using the Axios Get request response to update one of my state variables.

However, I am currently facing the problem in which because the state variable is being updated, App gets re-rendered, which then calls the Axios Get request again (causing a sorta infinite loop).

How do I make it so that a Get request can change a variable, but doesn’t re-render the component and call a Get request again?

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

function App(props) {
    let [sentenceData, setSentenceData] = React.useState({})

    const renderEnglishSentence = useCallback(function () {
        return <EnglishSentence sentenceData={sentenceData}/>;
    }, [sentenceData]);


    const fetchSentence = useCallback(function() {
        return axios.get('http://localhost:3030/getrandomunusedsentence')
    })

    fetchSentence().then((response) => 
        setSentenceData(response.data[0])
        return (
            <div>
                {renderEnglishSentence()}
            </div>
        )
    )
}

>Solution :

  const [sentenceData, setSentenceData] = React.useState({})

  React.useEffect(() => {
    axios.get('http://localhost:3030/getrandomunusedsentence')
      .then(() => {
        setSentenceData(response.data[0])
    })
  }, [])

You can make the http request in the useEffect hook with zero dependencies ([])

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