Formula Returns undefined in WeWeb While Console Logs Show Expected Results

Hi everyone,

I’m facing an issue where a formula for validating Brazilian postal codes (CEP) using the ViaCEP API is returning undefined in the WeWeb interface, even though the validation logic works correctly as evidenced by the console logs.

The formula is set up to return true for valid CEPs and false for invalid ones. Below, I’ve included the code, console logs, and a screenshot of the setup in WeWeb for context.


Code:

return (async () => {
  console.log("Starting CEP validation.");

  // Check if the value is provided and not empty
  if (!value || value.trim() === "") {
    console.log("Error: No CEP provided or it is empty.");
    return false; // Return false if the value is empty or missing
  }

  // Remove non-numeric characters
  const cep = value.replace(/[^\d]+/g, ''); 
  console.log(`CEP after removing non-numeric characters: ${cep}`);

  // Validate CEP format (must be 8 digits)
  const cepRegex = /^[0-9]{8}$/;
  if (!cepRegex.test(cep)) {
    console.log("Error: Invalid CEP format (must be 8 digits).");
    return false; // Return false if the format is invalid
  }

  const apiUrl = `https://viacep.com.br/ws/${cep}/json/`;
  console.log(`Querying ViaCEP API for CEP: ${cep}`);

  try {
    // Fetch the data from the API
    const response = await fetch(apiUrl);
    if (!response.ok) {
      console.log("Error: Unable to query the ViaCEP API.");
      return false;
    }

    const data = await response.json();
    if (data.erro) {
      console.log("Error: CEP not found in the ViaCEP database.");
      return false;
    }

    console.log("Valid CEP found in the ViaCEP API:", data);
    return true; // Return true if the CEP is valid and found
  } catch (error) {
    console.error("Unexpected error during CEP validation:", error);
    return false; // Return false in case of any errors
  }
})();


Console Logs:

Here are the console outputs for a valid CEP (01153000):

Starting CEP validation.
CEP after removing non-numeric characters: 01153000
Querying ViaCEP API for CEP: 01153000
Valid CEP found in the ViaCEP API: 
{cep: '01153-000', logradouro: 'Rua Vitorino Carmilo', complemento: '', unidade: '', bairro: 'Barra Funda', …}
bairro: "Barra Funda"
cep: "01153-000"
complemento: ""
ddd: "11"
estado: "São Paulo"
gia: "1004"
ibge: "3550308"
localidade: "São Paulo"
logradouro: "Rua Vitorino Carmilo"
regiao: "Sudeste"
siafi: "7107"
uf: "SP"
unidade: ""

Issue:

Although the console clearly shows the validation is working (with correct logging at each step), the formula returns undefined in WeWeb. This makes the validation logic unusable within my project.


Setup Context:

Attached is a screenshot of the formula setup within the WeWeb interface. The formula is saved as a global formula under the “Validation” folder and is linked to a field in the form.


Questions:

  1. Why does the formula return undefined in the WeWeb interface while the console logs the expected output?
  2. Is there a specific requirement for handling asynchronous functions in WeWeb formulas that I might be missing?
  3. Are there better practices for making async API calls in WeWeb to ensure consistent results?

formulas (and bound values) are sync functions, you can’t use async code because it will cause the kind of problem you are facing.
async code belongs to workflows, you can use a javascript action.
fetching data is better done in collections.

You can always await the code probably. WeWeb should support that.

The solution was implemented in three steps: first, a JavaScript formula was used to validate the input format (e.g., checking if the CEP has only numbers and exactly 8 digits). This ensured only properly formatted values would proceed.

Next, the WeWeb REST API plugin was used to call the external API (e.g., ViaCEP) with the validated input. The API response was then used to update a variable in WeWeb, dynamically populating the UI with the returned data or handling errors for invalid inputs. This approach effectively combined validation, API integration, and dynamic updates for a seamless user experience.