Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3694 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { IconButton, Typography } from '@mui/material';
import Edit from '@mui/icons-material/Edit';

import { axios } from '@utils';
import { addNotification } from '@store/notification/notification.actions';

import Widget from '@components/UI/Widget';
import LocationModal from './LocationModal';

const LocationCard = ({ address: defaultAddress = '', uuid = '', edit = false }) => {
  const [address, setAddress] = useState('');
  const [showModal, setShowModal] = useState(false);
  const labels = useSelector(({ intl }) => intl.labels);
  const dispatch = useDispatch();

  const toggleModal = () => setShowModal(!showModal);

  const handleEditLocation = (data) => {
    const formData = new FormData();
    Object.entries(data).map(([key, value]) => formData.append(key, value));

    axios
      .post(`/profile/my-profiles/location/${uuid}`, formData)
      .then((response) => {
        const { data, success } = response.data;

        if (!success) {
          const resError =
            typeof data === 'string'
              ? data
              : Object.entries(data)
                  .map(([key, value]) => `${key}: ${value}`)
                  .join(', ');

          throw new Error(resError);
        }

        setAddress(data.formatted_address);
        toggleModal();
      })
      .catch((error) => {
        dispatch(addNotification({ style: 'danger', msg: error.message }));
      });
  };

  useEffect(() => {
    setAddress(defaultAddress);
  }, [defaultAddress]);

  return (
    <>
      <Widget>
        <Widget.Header
          title={labels.location}
          renderAction={() => {
            if (!edit) return;
            return (
              <IconButton onClick={toggleModal}>
                <Edit />
              </IconButton>
            );
          }}
        />

        <Widget.Body>
          <Typography variant='body1'>{address}</Typography>
        </Widget.Body>
      </Widget>

      <LocationModal show={showModal} onClose={toggleModal} onConfirm={handleEditLocation} />
    </>
  );
};

export default LocationCard;