Home > front end >  Can not get .bns name from userSession.loadUserData() in React app using the Stacksjs package
Can not get .bns name from userSession.loadUserData() in React app using the Stacksjs package

Time:10-07

I am building an application for the Stacks Blockchain with Clarity smart contract language and Stacksjs on the frontend. From my React UI, I am unable to get the .bns name from the userSession object. From what I researched, it should be under userSession.loadUserData().username.

Below is the code snippet:

import { AppConfig, UserSession, showConnect } from "@stacks/connect";
import { Person } from "@stacks/profile";
import { Storage } from "@stacks/storage";
import appIcon from "./assets/app_logo.png";

const appConfig = new AppConfig(["store_write", "publish_data"]);

export const userSession = new UserSession({ appConfig });
export const storage = new Storage({ userSession });

console.log(userSession.loadUserData());

CodePudding user response:

The username property was recently deprecated in favor of letting the application handle retrieving BNS names. You can use this example file to see how you might pull the BNS name if you have the user's address.

import { StacksMainnet } from '@stacks/network';
import { fetchPrivate } from '@stacks/common';
import { AppConfig, UserSession, showConnect } from '@stacks/connect';
import { Person } from '@stacks/profile';

const appConfig = new AppConfig(['store_write', 'publish_data']);

export const userSession = new UserSession({ appConfig });

export function authenticate() {
  showConnect({
    appDetails: {
      name: 'Todos',
      icon: window.location.origin   '/logo.svg',
    },
    redirectTo: '/',
    onFinish: () => {
      window.location.reload();
    },
    userSession: userSession,
  });
}

export function getUserData() {
  return userSession.loadUserData();
}

export function getPerson() {
  return new Person(getUserData().profile);
}

export const network = new StacksMainnet();

export const fetchFirstName = async (address, network) => {
  try {
    const namesResponse = await fetchPrivate(
      `${network.bnsLookupUrl}/v1/addresses/stacks/${address}`
    );
    const namesJson = await namesResponse.json();
    if ((namesJson.names.length || 0) > 0) {
      return namesJson.names[0];
    }
  } catch (e) {}
  return undefined;
};

This was pulled from this commit that used to live in Hiro's example Todo application, although it looks like it has since been removed.

https://github.com/hirosystems/todos/pull/104/files#diff-41aaffe0a6b7fb309928aa1e15b50b58bc3348249614110efe07cf89da61c7a2

  • Related