Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 2646 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 www 1
import {axios} from "../../../utils";
2
import React, { useEffect, useRef, useState } from "react";
3
import { useForm } from "react-hook-form";
4
import { connect } from "react-redux";
5
import styled from "styled-components";
6
import { addNotification } from "../../../redux/notification/notification.actions";
7
import FormErrorFeedback from "../../../shared/form-error-feedback/FormErrorFeedback";
8
import Spinner from "../../../shared/loading-spinner/Spinner";
9
import UbicationInput from "../../../shared/ubication-input/UbicationInput";
10
 
11
const StyledSpinnerContainer = styled.div`
12
  position: absolute;
13
  left: 0;
14
  top: 0;
15
  width: 100%;
16
  height: 100%;
17
  background: rgba(255, 255, 255, 0.4);
18
  display: flex;
19
  justify-content: center;
20
  align-items: center;
21
  z-index: 300;
22
`;
23
 
24
const Location = (props) => {
25
  // redux destructuring
26
  const { addNotification } = props;
27
 
28
  // React hook form
29
  const {
30
    register,
31
    errors,
32
    handleSubmit,
33
    setValue,
34
    clearErrors,
35
    getValues,
36
    watch,
37
    setError,
38
  } = useForm();
39
 
40
  // states
41
  const [loading, setLoading] = useState(false);
42
 
43
  // refs
44
  const isAddressEmpty = useRef(true);
45
  const addressKeys = useRef([
46
    "address1",
47
    "address2",
48
    "country",
49
    "state",
50
    "city1",
51
    "city2",
52
    "postal_code",
53
    "latitude",
54
    "longitude",
55
  ]);
56
 
57
  useEffect(() => {
58
    addressKeys.current.map((addressKey) => {
59
      register(addressKey);
60
    });
61
    register("formatted_address", {
62
      required: "por favor seleccione una ubicación correcta",
63
    });
64
  }, []);
65
 
66
  const getAddressHandler = (addresObject) => {
67
    addressKeys.current.map((addressKey) => {
68
      setValue(addressKey, "");
69
    });
70
    const { address_components } = addresObject;
71
    if (address_components) {
72
      address_components.map((address_component) => {
73
        const address_component_name = address_component.long_name;
74
        const address_component_type = address_component.types[0];
75
        switch (address_component_type) {
76
          case "route":
77
            setValue("address1", address_component_name);
78
            break;
79
          case "sublocality":
80
            setValue("address2", address_component_name);
81
            break;
82
          case "locality":
83
            setValue("city1", address_component_name);
84
            break;
85
          case "administrative_area_level_2":
86
            setValue("city2", address_component_name);
87
            break;
88
          case "administrative_area_level_1":
89
            setValue("state", address_component_name);
90
            break;
91
          case "country":
92
            setValue("country", address_component_name);
93
            break;
94
          case "postal_code":
95
            setValue("postal_code", address_component_name);
96
            break;
97
          case "geometry":
98
            setValue("latitude", address_component.latitude);
99
            setValue("longitude", address_component.longitude);
100
            break;
101
          default:
102
            break;
103
        }
104
      });
105
      isAddressEmpty.current = false;
106
      clearErrors("formatted_address");
107
    } else {
108
      isAddressEmpty.current = true;
109
    }
110
    setValue("formatted_address", addresObject.formatted_address);
111
  };
112
 
113
  const handleOnSubmit = async (data) => {
114
    setLoading(true);
115
    const formData = new FormData();
116
    Object.entries(data).map(([key, value]) => {
117
      formData.append(key, value);
118
    });
119
    await axios
120
      .post("/account-settings/location", formData)
121
      .then((response) => {
122
        const resData = response.data;
123
        if (resData.success) {
124
          addNotification({
125
            style: "success",
126
            msg: resData.data.message,
127
          });
128
        } else {
129
          if (typeof resData.data === "object") {
130
            resData.data;
131
            Object.entries(resData.data).map(([key, value]) => {
132
              setError(key, { type: "manual", message: value[0] });
133
            });
134
          } else {
135
            const errorMessage =
136
              typeof resData.data === "string"
137
                ? resData.data
138
                : "Ha ocurrido un error, Por favor intente mas tarde";
139
            addNotification({
140
              style: "danger",
141
              msg: errorMessage,
142
            });
143
          }
144
        }
145
      });
146
    setLoading(false);
147
  };
148
 
149
  useEffect(async () => {
150
    setLoading(true);
151
    await axios.get("account-settings/location").then((response) => {
152
      const resData = response.data;
153
      if (resData.success) {
154
        Object.entries(resData.data).map(([key, value]) => {
155
          setValue(key, value);
156
        });
157
      }
158
    });
159
    setLoading(false);
160
  }, []);
161
 
162
  return (
163
    <div
164
      className="acc-setting"
165
      style={{
166
        position: "relative",
167
      }}
168
    >
169
      <h3>Básica</h3>
170
      <form onSubmit={handleSubmit(handleOnSubmit)}>
171
        <div className="cp-field">
172
          <label htmlFor="first_name">Ubicación</label>
173
          <div className="cpp-fiel">
174
            <UbicationInput
175
              onGetAddress={getAddressHandler}
176
              settedQuery={watch("formatted_address")}
177
            />
178
            <i className="fa fa-map-marker"></i>
179
          </div>
180
          {
181
            <FormErrorFeedback>
182
              {errors?.formatted_address?.message}
183
            </FormErrorFeedback>
184
          }
185
        </div>
186
        <div className="save-stngs pd2">
187
          <ul>
188
            <li>
189
              <button type="submit" className="btn-save-basic">
190
                Guardar
191
              </button>
192
            </li>
193
          </ul>
194
        </div>
195
        {/* <!--save-stngs end--> */}
196
        {/* <?php echo $this->form()->closeTag($form); ?>	 */}
197
      </form>
198
      {loading && (
199
        <StyledSpinnerContainer>
200
          <Spinner />
201
        </StyledSpinnerContainer>
202
      )}
203
    </div>
204
  );
205
};
206
 
207
// const mapStateToProps = (state) => ({
208
 
209
// })
210
 
211
const mapDispatchToProps = {
212
  addNotification: (notification) => addNotification(notification),
213
};
214
 
215
export default connect(null, mapDispatchToProps)(Location);