Proyectos de Subversion LeadersLinked - SPA

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
5 stevensc 1
import React, { useState, useEffect, useRef } from "react";
2
import FormErrorFeedback from "./FormErrorFeedback";
3
 
4
const UbicationInput = ({
5
  onGetAddress,
6
  settedQuery,
7
  placeholder = "Ubicación",
8
}) => {
9
  const [addresObject, setAddressObject] = useState({});
10
  const [query, setQuery] = useState("");
11
  const [error, setError] = useState("");
12
  const autoCompleteRef = useRef(null);
13
  let autoComplete;
14
 
15
  function handleScriptLoad(
16
    updateQuery,
17
    autoCompleteRef,
18
    setAddresObject,
19
    setError
20
  ) {
21
    autoComplete = new window.google.maps.places.Autocomplete(
22
      autoCompleteRef.current,
23
      { types: ["(cities)"] }
24
    );
25
    autoComplete.setFields([
26
      "address_components",
27
      "formatted_address",
28
      "geometry",
29
    ]);
30
    autoComplete.addListener("place_changed", () =>
31
      handlePlaceSelect(updateQuery, setAddresObject, setError)
32
    );
33
  }
34
 
35
  async function handlePlaceSelect(updateQuery, setAddresObject, setError) {
36
    const addressObject = autoComplete.getPlace();
37
 
38
    const query = addressObject.formatted_address;
39
    if (query) {
40
      setError("");
41
      updateQuery(query);
42
      setAddresObject({
43
        ...addressObject,
44
        address_components: [
45
          ...addressObject.address_components,
46
          {
47
            latitude: addressObject.geometry.location.lat(),
48
            longitude: addressObject.geometry.location.lng(),
49
            types: ["geometry"],
50
          },
51
        ],
52
      });
53
    } else {
54
      setError("$error_msg");
55
    }
56
  }
57
 
58
  useEffect(() => {
59
    handleScriptLoad(setQuery, autoCompleteRef, setAddressObject, setError);
60
  }, []);
61
 
62
  useEffect(() => {
63
    onGetAddress(addresObject, query);
64
  }, [addresObject]);
65
 
66
  return (
67
    <React.Fragment>
68
      <input
69
        type="text"
70
        id="location_search"
71
        name="location_search"
72
        className="form-control"
73
        placeholder={placeholder}
74
        ref={autoCompleteRef}
75
        onChange={(event) => {
76
          setAddressObject({});
77
          setQuery(event.target.value);
78
        }}
79
        value={settedQuery || query}
80
      />
81
      {error && <FormErrorFeedback>{error}</FormErrorFeedback>}
82
    </React.Fragment>
83
  );
84
};
85
 
86
export default UbicationInput;