react-places-autocomplete
react-places-autocomplete copied to clipboard
How can I fetch each value and put it into the rest of the inputs I have. They are all using things such as const [address, setAddress] = useState(shippingAddress.address); const [city, setCity] = useState(shippingAddress.city); const [state, setState] = useState(shippingAddress.state) const [postalCode, setPostalCode] = useState(shippingAddress.postalCode); const [country, setCountry] = useState(shippingAddress.country);
How can I fetch each value and add it to each input which uses state.
Here is an example of the state: const [address, setAddress] = useState(shippingAddress.address); const [city, setCity] = useState(shippingAddress.city); const [state, setState] = useState(shippingAddress.state) const [postalCode, setPostalCode] = useState(shippingAddress.postalCode); const [country, setCountry] = useState(shippingAddress.country);
@talmax1124 how did you end up handling this? I am trying to do the same thing
I'm doing the following:
const handleSelect = (value) => {
console.log('handleSelect: ', value)
const comps = value.split(','); // return has form `address, City, State, Country`
console.log('comps: ', comps);
setAddress(comps[0]);
setCity(comps[1]);
setCountry(comps[2]);
});
But it's not returning a zip code/postal code, so I have to figure that out.
@davidgs @talmax1124 @katherinepamina
I used the build in geocodeByAddress()
method, and then made a function that gets the address_component I want by type.
const getComponent = (address_components, type) => {
return address_components?.find((component) =>
component.types.includes(type)
);
};
const handleChange = (address) => {
let street = address.split(", ")[0];
setAddress(street);
setValue(name, street);
geocodeByAddress(address)
.then((results) => {
console.log(results);
let city = getComponent(
results[0].address_components,
"administrative_area_level_3"
);
if (typeof city === "undefined") {
city = getComponent(results[0].address_components, "locality");
}
if (typeof city !== "undefined") {
setValue("city", city.long_name);
}
let state = getComponent(
results[0].address_components,
"administrative_area_level_1"
);
if (typeof city !== "undefined") {
setValue("state", state.long_name);
}
let zipcode = getComponent(
results[0].address_components,
"postal_code"
);
if (typeof zipcode !== "undefined") {
setValue("zipcode", zipcode.long_name);
}
})
.catch((error) => {
console.error("ErrorXXX", error);
setValue("city", "");
setValue("state", "");
setValue("zipcode", "");
});
};