Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion src/components/CardAboutShelter/CardAboutShelter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,41 @@ import {
PawPrint,
Landmark,
Smartphone,
Building,
} from 'lucide-react';

import { Card } from '../ui/card';
import { ICardAboutShelter } from './types';
import { InfoRow } from './components';

const formatShelterAddressFields = (shelter: ICardAboutShelter['shelter']) => {
const fields = [];
if (shelter.street) fields.push(shelter.street);
if (shelter.streetNumber) fields.push(shelter.streetNumber);
if (shelter.neighbourhood) fields.push(shelter.neighbourhood);
if (shelter.zipCode) fields.push(shelter.zipCode);

return fields.join(', ');
};

const CardAboutShelter = (props: ICardAboutShelter) => {
const { shelter } = props;

const check = (v?: string | number | boolean | null) => {
return v !== undefined && v !== null;
};
const formatAddress =
shelter.address ??
`${formatShelterAddressFields(shelter)} - ${shelter.city}`;

return (
<Card className="flex flex-col gap-2 p-4 bg-[#E8F0F8] text-sm">
<div className="text-[#646870] font-medium">Sobre o abrigo</div>
<div className="flex flex-col flex-wrap gap-3">
<InfoRow icon={<Home />} label={shelter.address} />
<InfoRow icon={<Home />} label={formatAddress} />
{Boolean(shelter.city) && (
<InfoRow icon={<Building />} label={shelter.city} />
)}
<InfoRow
icon={<PawPrint />}
label={
Expand Down
10 changes: 8 additions & 2 deletions src/components/SearchInput/SearchInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,19 @@ import { cn } from '@/lib/utils';

const SearchInput = React.forwardRef<HTMLDivElement, ISearchInputProps>(
(props, ref) => {
const { value, onChange, className, ...rest } = props;
const {
value,
onChange,
className,
placeholder = 'Buscar por abrigo ou endereço',
...rest
} = props;

return (
<div ref={ref} className={cn(className, 'relative')} {...rest}>
<Input
value={value}
placeholder="Buscar por abrigo ou endereço"
placeholder={placeholder}
className="h-12 text-md font-medium text-zinc-600 pl-10 pr-4"
onChange={onChange}
/>
Expand Down
6 changes: 6 additions & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,21 @@ import { useFetch } from './useFetch';
import { usePaginatedQuery } from './usePaginatedQuery';
import { useThrottle } from './useThrottle';
import { useShelter } from './useShelter';
import { useShelterCities } from './useShelterCities';
import { useDebouncedValue } from './useDebouncedValue';
import { useSupplyCategories } from './useSupplyCategories';
import { useSupplies } from './useSupplies';
import { useViaCep } from './useViaCep';

export {
useShelters,
useFetch,
usePaginatedQuery,
useThrottle,
useShelter,
useShelterCities,
useDebouncedValue,
useSupplyCategories,
useSupplies,
useViaCep,
};
3 changes: 3 additions & 0 deletions src/hooks/useDebouncedValue/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { useDebouncedValue } from './useDebouncedValue';

export { useDebouncedValue };
27 changes: 27 additions & 0 deletions src/hooks/useDebouncedValue/useDebouncedValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { useState, useEffect } from 'react';

export const useDebouncedValue = (value: string, delay: number): string => {
const [debouncedValue, setDebouncedValue] = useState<string>(value);
const [currentValue, setCurrentValue] = useState<string>(value);

useEffect(() => {
setCurrentValue(value);
}, [value]);

useEffect(() => {
let timeoutId: NodeJS.Timeout;

if (currentValue !== debouncedValue) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
setDebouncedValue(currentValue);
}, delay);
}

return () => {
clearTimeout(timeoutId);
};
}, [currentValue, debouncedValue, delay]);

return debouncedValue;
};
15 changes: 10 additions & 5 deletions src/hooks/useFetch/useFetch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { api } from '@/api';
import { IServerResponse } from '@/types';
import { IUseFetchOptions } from './types';

function useFetch<T = any>(path: string, options: IUseFetchOptions<T> = {}) {
function useFetch<T = any>(path?: string, options: IUseFetchOptions<T> = {}) {
const { cache, initialValue } = options;
const [loading, setLoading] = useState<boolean>(true);
const [data, setData] = useState<T>(initialValue || ({} as T));
Expand All @@ -15,10 +15,15 @@ function useFetch<T = any>(path: string, options: IUseFetchOptions<T> = {}) {
const headers = config?.headers ?? {};
if (cache) headers['x-app-cache'] = 'true';
setLoading(true);
api
.get<IServerResponse<T>>(path, { ...config, headers })
.then(({ data }) => setData(data.data))
.finally(() => setLoading(false));

if (path) {
api
.get<IServerResponse<T>>(path, { ...config, headers })
.then(({ data }) => setData(data.data ?? (data as T)))
.finally(() => setLoading(false));
} else {
setLoading(false);
}
},
[cache, path]
);
Expand Down
1 change: 1 addition & 0 deletions src/hooks/usePaginatedQuery/paths.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export enum PaginatedQueryPath {
Shelters = '/shelters',
ShelterCities = '/shelters/cities',
SupplyCategories = '/supply-categories',
Supplies = '/supplies',
}
5 changes: 5 additions & 0 deletions src/hooks/useShelter/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
export interface IUseShelterData {
id: string;
name: string;
street?: string;
neighbourhood?: string;
city?: string;
streetNumber?: string | null;
zipCode?: string;
address: string;
pix?: string | null;
shelteredPeople?: number | null;
Expand Down
3 changes: 3 additions & 0 deletions src/hooks/useShelterCities/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { useShelterCities } from './useShelterCities';

export { useShelterCities };
4 changes: 4 additions & 0 deletions src/hooks/useShelterCities/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface IShelterCitiesData {
city: string;
sheltersCount: string;
}
9 changes: 9 additions & 0 deletions src/hooks/useShelterCities/useShelterCities.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { useFetch } from '../useFetch';
import { PaginatedQueryPath } from '../usePaginatedQuery/paths';
import { IShelterCitiesData } from './types';

export const useShelterCities = () => {
return useFetch<IShelterCitiesData[]>(PaginatedQueryPath.ShelterCities, {
cache: true,
});
};
1 change: 1 addition & 0 deletions src/hooks/useShelters/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export interface IUseSheltersData {
id: string;
name: string;
address: string;
city?: string;
pix?: string | null;
shelteredPeople?: number | null;
capacity?: number | null;
Expand Down
3 changes: 3 additions & 0 deletions src/hooks/useViaCep/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { useViaCep } from './useViaCep';

export { useViaCep };
12 changes: 12 additions & 0 deletions src/hooks/useViaCep/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export interface IViaCepData {
cep: string;
logradouro: string;
complemento: string;
bairro: string;
localidade: string;
uf: string;
ibge: string;
gia: string;
dd: string;
siafi: string;
}
10 changes: 10 additions & 0 deletions src/hooks/useViaCep/useViaCep.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { useFetch } from '..';
import { IViaCepData } from './types';

export const useViaCep = (cep: string | undefined) => {
const createdPath =
!cep || cep.length < 8
? undefined
: `https://viacep.com.br/ws/${cep}/json/`;
return useFetch<IViaCepData>(createdPath);
};
87 changes: 79 additions & 8 deletions src/pages/CreateShelter/CreateShelter.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { ChevronLeft } from 'lucide-react';
import { useEffect } from 'react';
import { ChevronLeft, Loader } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import ReactSelect from 'react-select';

import {
Select,
Expand All @@ -10,13 +12,16 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';

import { Header, TextField } from '@/components';
import { Button } from '@/components/ui/button';
import { ICreateShelter } from '@/service/shelter/types';
import { toast } from '@/components/ui/use-toast';
import { ShelterServices } from '@/service';
import { withAuth } from '@/hocs';
import { clearCache } from '@/api/cache';
import { hardCodedRsCities } from './hardcodedCities';
import { useDebouncedValue, useViaCep } from '@/hooks';

const CreateShelterComponent = () => {
const navigate = useNavigate();
Expand All @@ -31,7 +36,11 @@ const CreateShelterComponent = () => {
} = useFormik<ICreateShelter>({
initialValues: {
name: '',
address: '',
street: '',
neighbourhood: '',
city: '',
streetNumber: null,
zipCode: '',
shelteredPeople: 0,
capacity: 0,
verified: false,
Expand All @@ -45,14 +54,19 @@ const CreateShelterComponent = () => {
validateOnMount: false,
validationSchema: Yup.object().shape({
name: Yup.string().required('Este campo deve ser preenchido'),
address: Yup.string().required('Este campo deve ser preenchido'),
shelteredPeople: Yup.number()
.min(0, 'O valor mínimo para este campo é 0')
.nullable(),
capacity: Yup.number()
.min(1, 'O valor mínimo para este campo é 1')
.nullable(),
petFriendly: Yup.bool().nullable(),
street: Yup.string().required('Este campo deve ser preenchido'),
neighbourhood: Yup.string().required('Este campo deve ser preenchido'),
city: Yup.string().required('Este campo deve ser preenchido'),
streetNumber: Yup.string()
.min(0, 'O valor mínimo para este campo é 1')
.required('Este campo deve ser preenchido'),
zipCode: Yup.string().required('Este campo deve ser preenchido'),
contact: Yup.string().nullable(),
pix: Yup.string().nullable(),
}),
Expand All @@ -73,6 +87,18 @@ const CreateShelterComponent = () => {
}
},
});
const debouncedZipcode = useDebouncedValue(values?.zipCode ?? '', 500);

const { data: cepData, loading: isLoadingZipCodeData } =
useViaCep(debouncedZipcode);

useEffect(() => {
if (!cepData) return;

if (cepData.logradouro) setFieldValue('street', cepData.logradouro);
if (cepData.bairro) setFieldValue('neighbourhood', cepData.bairro);
if (cepData.localidade) setFieldValue('city', cepData.localidade);
}, [cepData, setFieldValue]);

return (
<div className="flex flex-col h-screen items-center">
Expand Down Expand Up @@ -103,11 +129,56 @@ const CreateShelterComponent = () => {
helperText={errors.name}
/>
<TextField
label="Endereço do abrigo"
{...getFieldProps('address')}
error={!!errors.address}
helperText={errors.address}
label="CEP"
{...getFieldProps('zipCode')}
error={!!errors.zipCode}
helperText={errors.zipCode}
/>
{Boolean(isLoadingZipCodeData) && (
<Loader className="animate-spin h-15 w-15 stroke-black" />
)}
<TextField
label="Logradouro (Rua/avenida)"
{...getFieldProps('street')}
error={!!errors.street}
helperText={errors.street}
/>
<TextField
label="Número"
{...getFieldProps('streetNumber')}
error={!!errors.streetNumber}
helperText={errors.streetNumber}
/>
<TextField
label="Bairro"
{...getFieldProps('neighbourhood')}
error={!!errors.neighbourhood}
helperText={errors.neighbourhood}
/>
<div className="flex flex-col gap-1 w-full">
<label className="text-muted-foreground">Cidade</label>
<ReactSelect
name="city"
placeholder="Cidade"
value={{
label: values.city,
value: values.city,
}}
options={hardCodedRsCities.map((item) => ({
value: item,
label: item,
}))}
onChange={(v) => {
setFieldValue('city', v?.value);
}}
className={`w-full ${
errors.city ? 'border-[1px] border-red-600 rounded-md' : ''
}`}
/>
{errors.city && (
<p className={'text-red-600 text-sm'}>{errors.city}</p>
)}
</div>
<TextField
label="Contato"
{...getFieldProps('contact')}
Expand Down
Loading