Reputation: 2553
I am learning next js. I want to call a function getItem
of https://www.npmjs.com/package/encrypt-storage
Using below code, but I am getting TypeError: EncryptStorage.getItem is not a function
import dynamic from 'next/dynamic';
const EncryptStorage = dynamic(() => import('encrypt-storage').then((mod) => mod.EncryptStorage(process.env.NEXT_PUBLIC_SKK)), { ssr: false });
console.log(EncryptStorage.getItem('aa'));
please help me to sort it out.
Upvotes: 2
Views: 5796
Reputation: 1479
tl;dr: You need to use await import(...)
instead of dynamic(() => import(...))
as the latter is only for components.
The longer version:
This was confusing to me as well as the docs don't outright state that you can't import modules with dynamic(...)
, only that it should be used to import components:
React components can also be imported using dynamic imports, but in this case we use it in conjunction with
next/dynamic
to make sure it works just like any other React Component.
And indeed, looking at this comment from a maintainer you can't use dynamic(...)
to import modules, only components.
Given this, here's a possible solution:
Also, note that .getItem(...)
is a method that needs to be called on an instance of EncryptStorage
.
// Needs to be ran in an `async` context or environment that supports top-level `await`s
const EncryptStorage = (await import("encrypt-storage")).default;
const encryptStorage = EncryptStorage(process.env.NEXT_PUBLIC_SKK);
console.log(encryptStorage.getItem("aa"));
And, here's a sandbox with a full working example.
Upvotes: 10