Last active
March 25, 2021 14:48
-
-
Save MGustav0/dac96f43bea5f119720f1bc71b90e35e to your computer and use it in GitHub Desktop.
Erro de envio de formulário
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { | |
RefObject, | |
useCallback, | |
useEffect, | |
useRef, | |
useState, | |
} from 'react'; | |
import { FormHandles, Scope } from '@unform/core'; | |
import { Form } from '@unform/web'; | |
import LocalShippingOutlinedIcon from '@material-ui/icons/LocalShippingOutlined'; | |
import * as Yup from 'yup'; | |
import { getCep, ItineraryProps } from '../../../services/address'; | |
import { useStepForm } from '../../../hooks/StepForm'; | |
import TextField from '../../TextField'; | |
import { Mask } from '../../TextField/types'; | |
import Autocomplete from '../../Autocomplete'; | |
import SelectState from '../../SelectState'; | |
import { | |
Container, | |
DeliveryTitle, | |
ZipCode, | |
Address, | |
Number, | |
Complement, | |
District, | |
City, | |
State, | |
Itinerary, | |
ItineraryError, | |
Observations, | |
} from './styles'; | |
interface DeliveryFormData { | |
cep: number; | |
endereco: string; | |
numero: number; | |
complemento: string; | |
bairro: string; | |
cidade: string; | |
estado: string; | |
frete: number; | |
observacao: string; | |
} | |
const DeliveryForm: React.FC<{ | |
setFormRef: (el: RefObject<FormHandles>) => void; | |
}> = ({ setFormRef }) => { | |
const { setFormData } = useStepForm(); | |
const [isValidZipCode, setIsValidZipCode] = useState(false); | |
const [itinerary, setItinerary] = useState(true); | |
const [cep, setCep] = useState(''); | |
const [itineraryOptions, setItineraryOptions] = useState<ItineraryProps[]>( | |
[], | |
); | |
const formRef = useRef<FormHandles>(null); | |
useEffect(() => { | |
setFormRef(formRef); | |
}, [setFormRef]); | |
const onBlurZipCode = useCallback( | |
async (event: any): Promise<void> => { | |
const { value } = event.target; | |
setCep(value); | |
const formattedCep = value?.replace(/[^0-9]/, ''); | |
if (formattedCep?.length !== 8) { | |
setIsValidZipCode(false); | |
formRef.current?.reset(); | |
} | |
try { | |
setIsValidZipCode(true); | |
const { endereco } = await getCep(formattedCep); | |
const itinerarySelect = endereco.itinerarios.map((item: any) => ({ | |
value: item.id, | |
text: item.nome, | |
})); | |
if (itinerarySelect) { | |
setItineraryOptions(itinerarySelect); | |
setItinerary(true); | |
} else { | |
setItinerary(false); | |
} | |
if (!itinerary) { | |
formRef.current?.reset(); | |
} | |
formRef.current?.setData({ | |
addressContainerScope: { | |
addressScope: { | |
address: endereco.logradouro, | |
}, | |
}, | |
districtContainerScope: { | |
districtScope: { | |
district: endereco.bairro, | |
}, | |
}, | |
stateContainerScope: { | |
cityScope: { | |
city: endereco.cidade, | |
}, | |
stateScope: { | |
state: endereco.uf, | |
}, | |
}, | |
}); | |
} catch (error) { | |
setIsValidZipCode(false); | |
setItinerary(false); | |
formRef.current?.reset(); | |
} | |
}, | |
[itinerary], | |
); | |
const handleSubmit = useCallback( | |
async (data: DeliveryFormData) => { | |
try { | |
const schema = Yup.object().shape({ | |
zipCode: Yup.number().required(), | |
address: Yup.string().required(), | |
number: Yup.number().required(), | |
complement: Yup.string(), | |
district: Yup.string().required(), | |
city: Yup.string().required(), | |
state: Yup.string().required(), | |
itinerary: Yup.string().required(), | |
shipping: Yup.number().required(), | |
referencePoint: Yup.string(), | |
}); | |
await schema.validate(data, { abortEarly: false }); | |
const { | |
endereco, | |
numero, | |
complemento, | |
bairro, | |
cidade, | |
estado, | |
frete, | |
observacao, | |
} = data; | |
const formData = { | |
cep, | |
endereco, | |
numero, | |
complemento, | |
bairro, | |
cidade, | |
estado, | |
frete, | |
observacao, | |
}; | |
setFormData(0, formData); | |
console.log('Formulário! ', formData); | |
console.log('Data! ', data); | |
} catch (error) { | |
console.log('Erro de validação: ', error); | |
formRef.current?.setErrors(error); | |
} | |
}, | |
[setFormData], | |
); | |
return ( | |
<Container> | |
<DeliveryTitle className="deliveryTitle"> | |
<LocalShippingOutlinedIcon /> | |
<span>Dados de entrega</span> | |
</DeliveryTitle> | |
<hr /> | |
<Form ref={formRef} onSubmit={handleSubmit}> | |
<Scope path="zipCodeScope"> | |
<ZipCode> | |
<TextField | |
label="CEP" | |
name="zipCode" | |
required | |
variationStyle="outlined" | |
mask={Mask.cep} | |
length={9} | |
onBlur={event => onBlurZipCode(event)} | |
/> | |
<a | |
href="https://enderecointer.correios.com.br/app/endereco/index.php?t" | |
target="_blank" | |
rel="noreferrer" | |
> | |
Não sabe o CEP? | |
</a> | |
</ZipCode> | |
</Scope> | |
{itinerary ? ( | |
<> | |
<Scope path="addressContainerScope"> | |
<div className="zipCode"> | |
<Scope path="addressScope"> | |
<Address> | |
<TextField | |
label="Logradouro" | |
name="address" | |
required | |
variationStyle="outlined" | |
mask={Mask.none} | |
length={20} | |
/> | |
</Address> | |
</Scope> | |
<Scope path="numberScope"> | |
<Number> | |
<TextField | |
label="Número" | |
name="number" | |
required | |
variationStyle="outlined" | |
mask={Mask.onlyNumber} | |
length={5} | |
/> | |
</Number> | |
</Scope> | |
</div> | |
</Scope> | |
<Scope path="districtContainerScope"> | |
<div className="complement"> | |
<Complement> | |
<TextField | |
label="Complemento" | |
name="complement" | |
variationStyle="outlined" | |
mask={Mask.none} | |
length={20} | |
/> | |
<span className="optional">opcional</span> | |
</Complement> | |
<Scope path="districtScope"> | |
<District> | |
<TextField | |
label="Bairro" | |
name="district" | |
required | |
variationStyle="outlined" | |
mask={Mask.none} | |
length={20} | |
/> | |
</District> | |
</Scope> | |
</div> | |
</Scope> | |
<Scope path="stateContainerScope"> | |
<div className="complement"> | |
<Scope path="cityScope"> | |
<City> | |
<TextField | |
label="Cidade" | |
name="city" | |
required | |
variationStyle="outlined" | |
mask={Mask.none} | |
length={20} | |
/> | |
</City> | |
</Scope> | |
<Scope path="stateScope"> | |
<State> | |
<SelectState id="estado" name="state" /> | |
</State> | |
</Scope> | |
</div> | |
</Scope> | |
{isValidZipCode ? ( | |
<div> | |
<Itinerary> | |
<Autocomplete | |
label="Itinerário" | |
name="itinerary" | |
required | |
id="itinerary" | |
placeholder="Selecione" | |
noOptionText="Nenhum itinerário disponível" | |
optionsRequest={() => itineraryOptions} | |
/> | |
</Itinerary> | |
<TextField | |
className="shipping" | |
label="Frete" | |
name="shipping" | |
required | |
mask={Mask.shipping} | |
length={16} | |
variationStyle="filled" | |
/> | |
</div> | |
) : ( | |
<Itinerary> | |
<Autocomplete disabled name="itinerary" /> | |
</Itinerary> | |
)} | |
<Observations> | |
<TextField | |
label="Observações" | |
name="referencePoint" | |
multiline | |
mask={Mask.none} | |
length={3000} | |
variationStyle="outlined" | |
/> | |
<span className="optional">opcional</span> | |
</Observations> | |
</> | |
) : ( | |
<ItineraryError | |
title={`Não foi localizado itinerário para o cep ${cep}. Por favor, informe outro CEP.`} | |
> | |
<Autocomplete disabled error name="itinerary" /> | |
</ItineraryError> | |
)} | |
</Form> | |
</Container> | |
); | |
}; | |
export default DeliveryForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment