I am trying to build a web3 project
I used wagmi to create a new project. This has nextjs included.
Now i wanted to use a database with my nextjs so i installed better-sqlite3
This is my code for the database
const sql = require("better-sqlite3");
const db = sql("pools.db");
const dummyPools = [
{
name: "USDC/WETH",
slug: "usdc-weth",
poolAddress:
"0xd2b6214e0dfc2bc5cb2e4eb6bf3b3b4ab7b71f56bf550c1953d1d47c7647c832",
token1Name: "USDC",
token2Name: "WETH",
token1Address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
token2Address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
},
];
db.prepare(
`
CREATE TABLE IF NOT EXISTS pools (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
name TEXT NOT NULL UNIQUE,
poolAddress TEXT NOT NULL UNIQUE,
token1Name TEXT NOT NULL UNIQUE,
token2Name TEXT NOT NULL UNIQUE,
token1Address TEXT NOT NULL UNIQUE,
token2Address TEXT NOT NULL UNIQUE
)
`
).run();
async function initData() {
const stmt = db.prepare(`
INSERT INTO pools VALUES (
null,
@slug,
@name,
@poolAddress,
@token1Name,
@token2Name,
@token1Address,
@token2Address
)
`);
for (const pool of dummyPools) {
stmt.run(pool);
}
}
initData();
I ran the script and got the database. Then to use it in my components i created a lib folder in the root directory and wrote this code
import sql from "better-sqlite3";
const db = sql("pools.db");
export function getPools() {
return db.prepare("SELECT * FROM pools").all();
}
Then to fetch items from the data base i used the getPools in my component like this
import { getPools } from "../../../lib/pools";
import PoolsGrid from "./pools/pools-grid";
export default function HomePage() {
const pools = getPools();
return (
<>
<PoolsGrid pools={pools} />
</>
);
}
This file is in the app/components directory
And in the frontend i am getting this error
Failed to compile
../node_modules/better-sqlite3/lib/database.js:2:1
Module not found: Can't resolve 'fs'
https://nextjs.org/docs/messages/module-not-found
Import trace for requested module:
../node_modules/better-sqlite3/lib/index.js
./lib/pools.js
./src/app/components/home-page.tsx
./src/app/page.tsx
This is what the structure looks like
folder structure
I have a function createPool which creates a pool with two tokens. I want this data to be pushed to the database and then HomePage is gonna fetch and display. For now i have created a dummy data and want it to be displayed on the HomePage component
Tarun Rao is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6