presiso que não tenha se não existir no cep, no endereco, por que se o cep nao tiver todas as informações ele fica com um virgula esquecido:
const viaCEP = () => {
const cepSemFormatacao = cep.replace('-', '');
fetch(https://opencep.com/v1/${cepSemFormatacao })
.then((response: { json: () => any; }) => response.json())
.then(async (data) => {
if (data.error){
const issuenogithub = await confirm(messageErroCEP, { title: 'CadDistrib - Erro, CEP', kind: 'warning' });
if (issuenogithub === true){
await open('https://github.com/Caua726/CadDistrib/issues/new');
} else {
console.log("Não Foi Criado");
}
} else {
const cidade = data.localidade;
setCidade(cidade);
const complemento = data.complemento
setComplemento(complemento);
let complementoFormatado = ", " + complemento;
const rua = data.logradouro
setRua(rua);
const bairro = data.bairro;
setBairro(bairro);
const estado = data.uf
const estadoObj = Estados.find(e => e.sigla === estado);
if (estadoObj) {
setEstado(estadoObj);
}
const endereco = rua,{numeroEndereco}compl{bairro } {estado};
setEndereco(endereco);
}
})
};
Assistant
e
m
e
n
t
o
F
or
ma
t
a
d
o
,
cidade−
Exemplos:
numero: 170. CEP: 08738-570
numero: 601. CEP: 28455-000
Rua Profeta Jonas, 170, , Vila Pomar Mogi das Cruzes - SP
, 601, , São José de Ubá - RJ
It looks like you're encountering issues with formatting your address string when certain components like rua (street), bairro (neighborhood), or complemento (complement) are missing from the API response. This results in extra commas or unexpected formatting in your address output.
To solve this problem, you'll need to conditionally include parts of the address only if they have values. Here's how you can adjust your code:
Check for undefined or empty strings: Before adding a component to your address string, check if it exists and is not empty.
Build the address dynamically: Use an array to collect the address components and join them with commas, ensuring that only non-empty components are included.
Here's how you can modify your viaCEP function:
javascript
const viaCEP = () => {
const cepSemFormatacao = cep.replace('-', '');
fetch(`https://opencep.com/v1/${cepSemFormatacao}`)
.then((response) => response.json())
.then(async (data) => {
if (data.error) {
const issuenogithub = await confirm(
messageErroCEP,
{ title: 'CadDistrib - Erro, CEP', kind: 'warning' }
);
if (issuenogithub === true) {
await open('https://github.com/Caua726/CadDistrib/issues/new');
} else {
console.log('Não Foi Criado');
}
} else {
const cidade = data.localidade;
setCidade(cidade);
const complemento = data.complemento || '';
setComplemento(complemento);
const rua = data.logradouro || '';
setRua(rua);
const bairro = data.bairro || '';
setBairro(bairro);
const estado = data.uf;
const estadoObj = Estados.find((e) => e.sigla === estado);
if (estadoObj) {
setEstado(estadoObj);
}
// Build the address components array
const enderecoComponents = [];
if (rua) enderecoComponents.push(rua);
if (numeroEndereco) enderecoComponents.push(numeroEndereco);
if (complemento) enderecoComponents.push(complemento);
if (bairro) enderecoComponents.push(bairro);
if (cidade) enderecoComponents.push(cidade);
if (estado) enderecoComponents.push(estado);
// Join the components with commas and add the state prefix
const endereco = enderecoComponents.join(', ');
setEndereco(endereco);
}
})
.catch((error) => {
console.error('Erro ao buscar o CEP:', error);
});
};
Explanation:
Default Values: Use the logical OR operator (||) to assign an empty string if a component is undefined or null:
javascript
const rua = data.logradouro || '';
Collect Non-Empty Components: Use an array (enderecoComponents) to collect address parts only if they have values:
javascript
if (rua) enderecoComponents.push(rua);
Join Components: Use join(', ') to combine the components with commas, which automatically handles cases where some components might be missing:
javascript
const endereco = enderecoComponents.join(', ');
State Formatting: If you need to separate the state with a hyphen or any other character, you can adjust the join logic or add it separately.
Resulting Address Output:
For numero: 170, CEP: 08738-570:
code
Rua Profeta Jonas, 170, Vila Pomar, Mogi das Cruzes, SP
For numero: 601, CEP: 28455-000:
code
601, São José de Ubá, RJ
Additional Notes:
Error Handling: Make sure to include a .catch block to handle any potential errors during the fetch operation.
State Object: Ensure that your Estados array contains the necessary state abbreviations and that estadoObj is correctly set.
User Input: Ensure that numeroEndereco and other user inputs are correctly captured and validated.
Refactoring for Clarity:
You can further refactor the code for better readability:
javascript
const viaCEP = async () => {
try {
const cepSemFormatacao = cep.replace('-', '');
const response = await fetch(`https://opencep.com/v1/${cepSemFormatacao}`);
const data = await response.json();
if (data.error) {
// Handle error as before
} else {
// Extract and set data with default empty strings
const cidade = data.localidade || '';
setCidade(cidade);
const complemento = data.complemento || '';
setComplemento(complemento);
const rua = data.logradouro || '';
setRua(rua);
const bairro = data.bairro || '';
setBairro(bairro);
const estado = data.uf || '';
const estadoObj = Estados.find((e) => e.sigla === estado);
if (estadoObj) {
setEstado(estadoObj);
}
// Build address
const enderecoComponents = [
rua,
numeroEndereco || '',
complemento,
bairro,
cidade,
estado,
].filter(Boolean); // Removes empty strings
const endereco = enderecoComponents.join(', ');
setEndereco(endereco);
}
} catch (error) {
console.error('Erro ao buscar o CEP:', error);
}
};
Using filter(Boolean):
This method filters out any falsy values (false, 0, '', null, undefined, NaN) from an array.
This way, you don't need to individually check each component before adding it to the array.
Example Usage:
Suppose you have the following data:
javascript
const data = {
logradouro: '', // Empty street
localidade: 'São José de Ubá',
bairro: '', // Empty neighborhood
uf: 'RJ',
complemento: '', // Empty complement
};
const numeroEndereco = '601';
The enderecoComponents array after filtering will be:
javascript
['601', 'São José de Ubá', 'RJ']
And the resulting endereco string will be:
code
601, São José de Ubá, RJ
Final Thoughts:
By dynamically building your address string based on the available data, you ensure that there are no extra commas or misplaced components, resulting in a clean and accurate address format.