58
loading...
This website collects cookies to deliver better user experience
const { data, isValidating, revalidate, error } = useSWR(key, fetcher)
npx create-next-app useswr-demo
npm i mongodb @vercel/node
const MongoClient = require("mongodb").MongoClient;
let cachedDb = null;
export const connectToDatabase = async () => {
if (cachedDb) {
console.log("Using existing DB connection");
return Promise.resolve(cachedDb);
}
return MongoClient.connect(process.env.MONGODB_URI, {
native_parser: true,
useUnifiedTopology: true,
})
.then((client) => {
let db = client.db("truskin-storage"); // free version
console.log("New DB Connection");
cachedDb = db;
return cachedDb;
})
.catch((error) => {
console.log("Mongo connect Error");
console.log(error);
});
};
// Import Dependencies
import { connectToDatabase } from '../lib/database';
module.exports = async (req, res) => {
const db = await connectToDatabase();
if (req.method === 'GET') {
const collection = await db.collection('todos');
const todos = await collection.find({}).toArray();
res.status(200).json({ todos });
} else if (req.method === 'POST') {
const newtodo = req.body;
const collection = await db.collection('todos');
const todos = await collection.insertOne(newtodo);
res.status(200).json({ todos, status: 'API called sucessfully' });
} else {
res.status(404).json({ status: 'Error route not found' });
}
};
{
"env": {
"MONGODB_URI": "@mongodb-ur"
},
"headers": [
{
"source": "/(.*)",
"headers": [
{
"key": "Access-Control-Allow-Origin",
"value": "*"
}
]
}
]
}
npm i axios
import Head from 'next/head';
import Image from 'next/image';
import axios from 'axios';
import styles from '../styles/Home.module.css';
export default function Index(props) {
const todoList = props.data;
return (
<div className={styles.container}>
<Head>
...
</Head>
<main className={styles.main}>
<ul>
{todoList.map((todo, index) => (
<li key={index}>
<a>{todo.task}</a>
</li>
))}
</ul>
</main>
<footer className={styles.footer}>
...
</footer>
</div>
);
}
export const getStaticProps = async () => {
const res = await axios.get('http://localhost:3000/api/todos');
return {
props: { data: res.data.todos },
};
};
http://localhost:3000/api/todos
http://localhost:3000
npm install swr
import axios from 'axios';
import useSWR from 'swr';
import styles from '../styles/Home.module.css';
export default function Users() {
const address = 'http://localhost:3000/api/todos';
const fetcher = async (url) =>
await axios.get(url).then((res) => res.data.todos);
const { data, error } = useSWR(address, fetcher, {
revalidateOnFocus: true, // auto revalidate when the window is focused
});
if (error) <p>Loading failed...</p>;
if (!data) <h1>Loading...</h1>;
return (
<div>
<main className={styles.main}>
<div className="container">
{data && (
<ul>
{data.map((todo, index) => (
<li key={index}>
<a>{todo.task}</a>
</li>
))}
</ul>
)}
</div>
</main>
</div>
);
}
http://localhost:3000/api/todos
http://localhost:3000/todos