I'm getting an infinite loop with this code.
I've been trying some of the solutions from another posts but they don't work.
locationAddress
is an array of addresses and I'm trying to get the coordinates using the Google Maps Geocode API.
const reducer = (state, action) => {
switch (action.type) {
case 'add':
return [
...state,
{
address: action.address,
name: action.name,
id: action.id
}
];
case 'remove':
return state.filter((_, index) => index !== action.index)
default:
return state;
}
}
const [locationAddress, setLocationAddress] = useReducer(reducer, []);
const [coordinates, setCoordinates] = useState([]);
useEffect(() => {
const fetchLocation = async () => {
for(let i = 0; i < locationAddress.length; i++) {
const response = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
params: {
address: locationAddress[i].address,
key: 'MyAPIKey'
}
})
.then(response => {
setLocationAddress({locationAddress: response.data});
setCoordinates([...coordinates, {lat: response.data.results[0].geometry.location.lat, lng: response.data.results[0].geometry.location.lng}]);
}
)
.catch(error => {
console.log(error)
});
}
}
fetchLocation();
},[coordinates, locationAddress]);