DEV Community

Andrés Rossini
Andrés Rossini

Posted on

I don't know how to use an attribute of a JSON

I was looking for access an JSON attribute in JavaScript, that come from an aspnet (so for that is the dotnet tag).

This is the JSON from the API

The connection with js and aspnet is this:

function PostAsociado()
{
    const sePuedeCargar = AsociadoCanPost(); 
    const AsociadoObject = SetAsociadoObject();
    var htmlState = document.getElementById('StateExecution');

    const response = fetch(urlAsociado,
        {
            method : 'POST',
            headers: 
            {
            'accept' : 'application/json',
            'Content-Type' : 'application/json',    
            },
            body : JSON.stringify(AsociadoObject) 
        })
        .then(response => response.json())

        alert(response.executionSuccessful);

    if(response.executionSuccessful)
    {
        htmlState.innerHTML = "El asociado " +asociado.Nombre + " "+ asociado.Apellido  +" se ha cargado exitosamente.";
        htmlState.style.color = "green"; htmlState.style.display = "inherit"; 
    }
    else
    {
        htmlState.innerHTML = "El dni ya fue ingresado.";
        htmlState.style.color = "red"; htmlState.style.display = "inherit";
    }
}

Enter fullscreen mode Exit fullscreen mode

This is the response class, the language used is C#, (each class have their own file, I just display in that way because is more easy to understand):

    public abstract class Response
    {
        public bool ExecutionSuccessful {get; set;}
        public string? ErrorMessage {get;set;}
    }

  public class AsociadoPostResponse: Response
    {
        public Asociado? asociado {get; set;}
    }


Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
tutinio1313 profile image
Andrés Rossini • Edited

If anybody have this problem, the error reason is because the code call the API and dont wait for the response. So if you need the response for anything (like a calculus or show some attribute) the code does not have that info and that keeps "pendind" or "promise".

I tried the following, make the function an async function (that is an asynchronous and that permits await the response) also I write an await before the fetch.

dev-to-uploads.s3.amazonaws.com/up...