Issue of localstorage

Language : typescript Version 4.1.3
Framework: next 12.1.5
moralis : 1.5.10
react-moralis : 1.3.5

image

Got below info when yarn build.

[    ] info  - Generating static pages (0/6)It looks like you're using the browser version of the SDK in a node.js environment. You should require('moralis/node') instead.
It looks like you're using the browser version of the SDK in a node.js environment. You should require('moralis/node') instead.
It looks like you're using the browser version of the SDK in a node.js environment. You should require('moralis/node') instead.
user ======> null
/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/moralis/lib/browser/StorageController.browser.js:23
    return localStorage.getItem(path);
    ^

ReferenceError: localStorage is not defined
    at Object.getItem (/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/moralis/lib/browser/StorageController.browser.js:23:5)
    at Object.getItemAsync (/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/moralis/lib/browser/Storage.js:54:48)
    at Object.currentInstallationId (/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/moralis/lib/browser/InstallationController.js:34:29)
    at Object.request (/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/moralis/lib/browser/RESTController.js:387:54)
    at Object.run (/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/moralis/lib/browser/Cloud.js:172:34)
    at run (/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/moralis/lib/browser/Cloud.js:98:52)
    at Function.<anonymous> (/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/moralis/lib/browser/MoralisWeb3.js:885:39)
    at tryCatch (/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/regenerator-runtime/runtime.js:63:40)
    at Generator.invoke [as _invoke] (/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/regenerator-runtime/runtime.js:294:22)
    at Generator.next (/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/regenerator-runtime/runtime.js:119:21)
/Volumes/macOSdat/frontend/bcProject/moralis/moralis-dashboard6/node_modules/moralis/lib/browser/StorageController.browser.js:23
    return localStorage.getItem(path);
    ^

Can we see how you’re using local storage in code? It looks like Next is trying to run it on the server side or Node which won’t work.

One way to do things is to use local storage in a useEffect to force it to run in the browser.

@skylon.jose it looks like you have not correctly imported Moralis SDK in your node/next project
You are importing in the react way i.e. import { MoralisProvider } from "react-moralis";

check out the doc: https://docs.moralis.io/moralis-dapp/connect-the-sdk/connect-using-node

for nodejs, the correct way is : const Moralis = require("moralis/node");

Tried, got as below.

image

image

If both _app.tsx and Balance.tsx, change to import Moralis from 'moralis/node.js' , then another issue as below :

Maybe, my problem is where to put the Moralis.start ?

1 or 2, is right?

No, there is no any code related with localStorage, but, have no idea about next and moralis, where they used it.

You can take a look at the ethereum-nextjs-boilerplate https://github.com/ethereum-boilerplate/ethereum-nextjs-boilerplate/blob/main/src/pages/_app.jsx

Yes, have read this link, and per this link, there should be no need for moralis.start

No need of moralis.start as the provider will handle that.

Yes, removed all the moralis.start from both _app.tsx and index.tsx, yarn build pass.

But, after yarn dev (no warning and error), when access from chrome, got below error:

import Moralis from "moralis";
// import Moralis from "moralis/node.js";
import { useEffect, useState, useCallback } from "react";
import { Box, Text, Divider, Image } from "@chakra-ui/react";
import { useMoralisWeb3Api } from "react-moralis";
import CustomContainer from "../CustomContainer";

// const Moralis = require("moralis/node");
type MyProps = {
  user: Moralis.User<Moralis.Attributes> | null;
  account: string | null;
};
type ChainType =
  | "eth"
  | "0x1"
  | "ropsten"
  | "0x3"
  | "rinkeby"
  | "0x4"
  | "goerli"
  | "0x5"
  | "kovan"
  | "0x2a"
  | "polygon"
  | "0x89"
  | "mumbai"
  | "0x13881"
  | "bsc"
  | "0x38"
  | "bsc testnet"
  | "0x61"
  | "avalanche"
  | "0xa86a"
  | "avalanche testnet"
  | "0xa869"
  | "fantom"
  | "0xfa"
  | undefined;

type TokenBalaProp = {
  token_address: string;
  name: string;
  symbol: string;
  logo?: string | undefined;
  thumbnail?: string | undefined;
  decimals: string;
  balance: string;
}[];

export default function Balance({ user, account }: MyProps) {
  const Web3API = useMoralisWeb3Api();
  const chainId = Moralis.getChainId() as ChainType;

  const [ethBalance, setEthBalance] = useState<string | undefined>();
  const [tokBalance, setTokBalance] = useState<TokenBalaProp | undefined>();

  // 1. Native Balance
  const fetchNativeBalance = useCallback(async () => {
    const nativeBala = await Web3API.account.getNativeBalance({
      chain: chainId,
      address: account!,
    });
    if (nativeBala && nativeBala.balance) {
      setEthBalance(Moralis.Units.FromWei(nativeBala.balance));
    }
  }, [Web3API.account, account, chainId]);

  // 2. ERC20 Balance
  const fetchTokenBalances = useCallback(async () => {
    const tokenBalances = await Web3API.account.getTokenBalances({
      chain: chainId,
      address: account!,
    });
    console.log("token balances", tokenBalances);
    if (tokenBalances) {
      setTokBalance(tokenBalances);
    }
  }, [Web3API.account, account, chainId]);

  useEffect(() => {
    fetchNativeBalance();
    fetchTokenBalances();
  }, [Web3API.account, fetchNativeBalance, fetchTokenBalances]);

  return (
    <CustomContainer>
      <Text mb="6" fontSize={"xl"} fontWeight="bold">
        My NativeBalance
      </Text>
      {ethBalance && (
        <Text>
          πŸ’²&nbsp; {ethBalance} <b>ETH</b>
        </Text>
      )}
      <Divider></Divider>
      {tokBalance &&
        tokBalance.map((token) => (
          <div key={token.token_address}>
            <Box display={{ md: "flex" }}>
              {token.logo && (
                <Image alt="img" boxSize="24px" src={token.logo} />
              )}{" "}
              <Text>
                {" "}
                &nbsp;{" "}
                {Moralis.Units.FromWei(token.balance, Number(token.decimals))}
                <b>{token.symbol}</b> - <b>{token.token_address}</b>
              </Text>
            </Box>
          </div>
        ))}
    </CustomContainer>
  );
}

You can add isInitialized to your dependencies here which is gotten from useMoralishook and then you can warp everything in the fetchTokenBalances function in if(isInitialized){ ...Your code goes here }