Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my axios get call repeating over and over using React.useEffect to fetch from Rails backend?

I am using axios on a React w/ Hooks front end to make a get request to populate my react-google-maps/api GoogleMaps Marker components using seed data in my rails backend. When I let the rails server run, the server repeatedly makes this call.

The following line causes the axios.get to be called on a loop:

 React.useEffect(() => {
        // Get Coordinates from api
        // Update Coordinates in state
        axios.get('/api/v1/coordinates.json')
        .then(response => response.data.data.map(coord => 
              setCoordinateFromApi(coord.attributes)))
        .catch(error => console.log(error))
    }, [coordinates.length]) 

This successfully populates the map but means I can't use onClick's functionality (because I presume the stack is being topped with this request?)

My index method on my CoordinatesController in Rails:

def index
  coordinates = Coordinate.all
  render json: CoordinateSerializer.new(coordinates).serialized_json
end

NB: this is my first project linking React to Rails as well as using Hooks

like image 800
bashford7 Avatar asked May 22 '20 16:05

bashford7


People also ask

How do you use Axios in react useEffect?

Use the Axios HTTP Client with the React useEffect Hook We can make HTTP requests when the component mounts by calling the useEffect hook with an empty array in the 2nd argument. We define the getData function to make a GET request with the axios. get method. The function is async since axios methods return a promise.

How do you respond to react Axios?

First, you import React and Axios so that both can be used in the component. Then you hook into the componentDidMount lifecycle hook and perform a GET request. You use axios. get(url) with a URL from an API endpoint to get a promise which returns a response object.


1 Answers

I would assume that you have this useState defined above:

const [coordinated, setCoordinatesFromApi] = useState([])

If it is, then this is the root cause:

React.useEffect(() => {
  axios.get(...).then(coordinates => setCoordinateFromApi(coord.attributes))
}, [coordinates.length])

By doing so, you ask React.useEffect to always call axios.get whenever coordinates.length change. Which will make this useEffect an infinite loop (because you always change the coordinates value whenever the axios request finish).

If you only want to execute it once, you should just pass an empty array on the useEffect, like this

React.useEffect(() => {
  axios.get(...).then(coordinates => setCoordinateFromApi(coord.attributes))
}, [])

That way, your axios.get will only be called once and you will no longer have infinite loop

like image 69
Devin Ekadeni Avatar answered Oct 22 '22 12:10

Devin Ekadeni