3

I am using React+Typescript and trying to retrieve data from a struc using a query subscription. I first tried the following in order to check that I'm retrieving the right data:

api.query.rolesModule.requestedRoles(address, (data: Codec) => {
      let data0 = data.toString();
      console.log('In session:' + data0);
    }

the string returned is the following:

In session:{"accountId":"5D1nJ8*************uc5e3AuB","role":"SELLER","block":2600,"proposalHash":"0xf0e4d3819cad58b9b7a521968202192601654106b063ed550d45e949cd0f9eec","proposalIndex":0,"sessionClosed":false,"approved":false}

Now what I really want are the role and block fields. I tried the following:

 api.query.rolesModule.requestedRoles(
      address,
      ({ block, role }: { block: number; role: string }) => {
        let data0 = block;
        let data1 = role;
        console.log('In session:' + data0 + ' & ' + data1);
      }

but both results are undefined (which is not actually the case). I did my best to emulate the example in the polkadot.js API doc, and had success in the following case to recover the free balance:

 api.query.system.account(address, ({ data: free }: { data: { free: BN } }) => {
      let { free: balance1 } = free;

What am I missing?

Edit1: This is the storage I am trying to get data from:

#[pallet::storage]
    #[pallet::getter(fn get_requested_role)]
    pub type RequestedRoles<T: Config> =
        StorageMap<_, Twox64Concat, AccountIdOf<T>, Proposal<T>, OptionQuery>;

with proposal being:

pub struct Proposal<T: Config>{
    pub account_id: T::AccountId,
    pub role: Option<Accounts>,
    pub block: BlockNumberOf<T>,
    pub proposal_hash: T::Hash,
    pub proposal_index: u32,
    pub session_closed: bool, 
    pub approved: bool,
}

thanks in advance Kazu

1 Answer 1

1

You can call toHuman() it returns Human-parsable JSON structure with values formatted as per the settings.

This example will return you the values you are trying to get.

api.query.templateModule.requestedRoles(address, (data: any) => {
        let data0 = data.toHuman();
        console.log(data0.role);
        console.log(data0.block);
});

toHuman() returns an any, if you want to have it all typed I suggest you create a parse function that get this any input an returns your custom type Proposal

3
  • Thanks Alex!! this exactly what I needed!!I only wish I could use another type than any for data, as I'm on TS...... Aug 3, 2023 at 9:00
  • WIth the Codec you were using doesn't work?
    – Alex Bean
    Aug 3, 2023 at 9:42
  • no, it does not find the different fields with codec Aug 3, 2023 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.