1

I'm currently trying to pass in a location for forward geocoding and can't figure out why my call seems to be triggering an infinite loop.

I'm trying to pass in the locations using a map and then use the response from the API elsewhere in my code.

Here's my data provider...

import React, {
  useEffect,
  useState
} from "react"

export const GeoCodeContext = React.createContext()

export const GeoCodeProvider = (props) => {
  const [latLong, setLatLong] = useState([])

  const getLatLong = (location) => {

    return fetch(`https://api.opencagedata.com/geocode/v1/json?q=${location}&key=MYKEY&limit=1`)
      .then(res => res.json())
      .then(setLatLong)
  }

  return (
    <GeoCodeContext.Provider value={{latLong,getLatLong}}>
    {props.children}
    </GeoCodeContext.Provider>
  )
}

Here's where the function is being called

import React, { useContext } from "react"
import {GeoCodeContext} from "./GeoCodeProvider"
import {LogContext} from "../divelog/DiveLogProvider"

export const MapRender = () =>{
    const {diveLogs} = useContext(LogContext)
    const {latLong, getLatLong} = useContext(GeoCodeContext)
    

    diveLogs.map(dl =>{
        //getLatLong(dl.location)
        //console.log(latLong) -- returns an endless log of api calls
    })

    

    return <h2>GeoCode Render</h2>
}

1 Answer 1

1

Every time your MapRender component renders, it calls getLatLong once for every dive log.

getLatLong ultimately triggers a call to setLatLong...

...which causes GeoCodeProvider to re-render...

...which causes MapRender (among other things) to re-render...

and we go back to the beginning of the loop.

Consider wrapping MapRender's call to getLatLong in a call to the useEffect hook to avoid triggering it every render.

Sign up to request clarification or add additional context in comments.

2 Comments

Please try giving a [qualified] solution rather than reiterating the problem. 'wrapping MapRender's call to getLatLong...' is just not useful.
The OP "can't figure out why my call seems to be triggering an infinite loop." The answer explains why the infinite loop is happening and suggests what to do to avoid the problem, with a link to relevant documentation. I encourage you to propose an edit rather than critiquing the answer in the comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.