Manipulating Async/Await function return with JSON.parse - REACTJS

Asked

Viewed 46 times

0

I have the code below that is returning an error where I am not understanding how to solve. The log console of "Ret.value" returns {"id":1,"name":"Max"} string correctly, but in JSON.parse.

Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.

/

  async getObject() {
   const ret = await Storage.get({ key: 'user' });
   console.log(JSON.parse(ret.value)); // ERRO AQUI
   console.log(JSON.parse('{"id":1,"name":"Max"}')); // SEM ERRO TUDO RETORNA NORMAL
 }

I’m using Ionic with Reactjs, in Typescript.

I think it should be something simple, but I tried several examples and looked here, but nothing solved the problem.

1 answer

1


The problem is happening because your kind ret.value is a union between string and null.

Even if in your test he’s a string, the declaration of this kind includes the possibility that it null also, and the guy null is not a valid parameter for the method JSON.parse, so the compiler is not accepting the same.

To pass the parameter to the method JSON.parse, you can use one of the many Shields typescript. If you add a if to make sure that ret.value is the type string within a given scope, this will already be enough for the compiler to make sure that it is valid:

async getObject() {
    const ret = await Storage.get({ key: 'user' });
    if (typeof ret.value === 'string') {
        // dentro desse escopo você pode utilizar ret.value como se ele sempre fosse uma string
        console.log(JSON.parse(ret.value));
    }
}

Another approach you can use is to create a variable that is of the type string, and exclusively string:

async getObject() {
    const ret = await Storage.get({ key: 'user' });
    const value = ret.value ?? '';
    console.log(JSON.parse(value));
}

In the above example, if ret.value for null the operator coalesces (??) will result in the empty string, so the type of value it can’t be null, logo is a valid parameter for JSON.parse

  • Thank you very much :) It worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.