I have tried disabling reactStrictMode in next.config.js but it's not the problem. My code is just connecting to MongoDB and finding a user in the database and returning the user. Here is my component:
export const revalidate = 20;
async function getUsers() {
const client = await clientPromise;
const db = client.db("local");
const data = await db
.collection("users")
.find({ email: "bob123#gmail.com" })
.toArray();
console.log("THIS IS THE SERVER RUNNING");
return data;
}
export default async function Home() {
const users = await getUsers();
if (!users) return notFound();
return (
<main className={styles.main}>
{users?.map((user) => (
<p key={user._id}>{user.name}</p>
))}
</main>
);
}
Even in build mode, I still get my console.log() of "THIS IS THE SERVER RUNNING" printed out twice as you see below in the terminal. This happens every 20 seconds because of my revalidation setting.
My worry here is every 20 seconds I'm revalidating data twice, when it should only be once.
Anyone have any fix or explanation for this? Or could it possibly be a bug in Nextjs 13?
Related
I'm trying to get Vuefire Storage to wait for a file to finish uploading so that I can get the image URL and update Auth and the Firestore. The upload() method is supposed to return a promise, but it doesn't seem to wait for it to resolve before executing the code in .then()
const submit = async () => {
const storage = useFirebaseStorage()
const avatarFileRef = storageRef(storage, fileName.value)
const { url, upload, uploadProgress } = useStorageFile(avatarFileRef)
await upload(file.value[0])!
.then(() => {
if (uploadProgress.value == 1) {
console.log(url.value)
updateAuth(url.value!)
}
})
.catch((error) => {
console.log(error)
// file save error message
})
}
console.log(url.value) is returning null.
I think it is related to the issue i had. I raised it to Eduardo, maintainer of vuefire. Currently there is no way around it. You can see the thread here. It will probably be fixed in the next version.
Half an hour ago I was writing Next.js. Everything was good and okay then suddenly my application stopped http requests.
export async function getStaticProps() {
try{
const res = await Promise.all([
axios.get(`${process.env.API_URL}announcements?page=1&limit=3`),
axios.get(`${process.env.API_URL}executives?sort=createdAt`)
]);
const initAnnouncements = res[0]?.data.data.data
const initExecutives = res[1]?.data.data.data
return {
props: {
initAnnouncements,
initExecutives
}
}
} catch {return {notFound: true}}
}
The data property of the above promise is some crazy random string. I tried with fetch and I got [{}{}]. What is going on here any solutions?
Edit: My Node server works very-well. I can reach above paths from browser and successfully get the data.
PS: I fixed the problem. No answer needed.
In my project I'm using NextJs and tRPC for backend calls. I wanted to fetch some data in getServerSideProps using tRPC and provide it in Page component, also using react-query state for whole application. Here's my _app withTRPC config
export default withTRPC<AppRouter>({
config({ ctx }) {
const url = `${getBaseUrl()}/api/trpc`;
return {
url,
transformer: superjson,
queryClientConfig: { defaultOptions: { queries: { staleTime: 60 } } },
};
},
ssr: false,
})(MyApp);
I used ssr: false because of 'bug' in NextJs, which will cause to return empty props for first render, if set to true.
Here's my getServerSideProps function on the page
export const getServerSideProps = async () => {
const ssg = createSSGHelpers({
router: appRouter,
ctx: await createContext(),
transformer: superjson,
});
const entryRD = await getPageBySlug(option.some("trados"))();
await ssg.prefetchQuery("contentful.getProductList");
console.log("==>props", entryRD, ssg.dehydrate());
return {
props: {
trpcState: ssg.dehydrate(),
entryRD,
},
};
};
When I log to the console on server, both values are there, entryRD and ssg.dehydrate(). The latter contains object with mutations and queries and also data with correctly fetched data. Here is my page code:
const Page = ({ entryRD, trpcState }: InferGetServerSidePropsType<typeof getServerSideProps>) => {
const { data, isLoading } = trpc.useQuery(["contentful.getProductList"]);
console.log("==>data", data, isLoading);
return isLoading ? <div>Loading...</div> : <EntryCompontn entry={entryRD} />
When I read the docs, I understand it like:
fetch data on server,
use ssg.dehydrate() to return cache to component
when you use trpc.useQueried(), it will return cached value from state
Unfortunately data is empty and isLoading is true for a brief moment, when data is fetched. Did I misunderstood something, or did I make a mistake?
Let's say we have firebase project in which we have to use RTDB.
In RTDB we have created multiple databases.
I created a cloud trigger function i.e .onCreate so that my both databases get updated whenever I update any of two. When I am creating anything in default database it is working completely fine but when I am trying to update through other database (other than default one) it doesn't update default one. So could you please help me on this?
/* eslint-disable */
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
//this method is updating on creating data on database mentioned in instance id
export const newTest1=functions.database.instance('flysample-75b81-227ae').ref('/msg')
.onCreate((snapshot, context) => {
let app = admin.app();
app.database('https://flysample-75b81.firebaseio.com/').ref('/db1').set({Name:"Database1"})
app.database('https://flysample-75b81-227ae.firebaseio.com/').ref('/db1').set({Name:"Database1"})
return "done";
});
//this method is updating only by creating data on default database
export const newTest2=functions.database.ref('/msg')
.onCreate((snapshot, context) => {
let app = admin.app();
app.database('https://flysample-75b81.firebaseio.com/').ref('/db1').set({Name:"Database1"})
app.database('https://flysample-75b81-227ae.firebaseio.com/').ref('/db1').set({Name:"Database1"})
return "done";
});
//below 2 method works fine but i want to do this by single function
export const myFunTest1 = functions.database.instance('flysample-75b81').ref('/name')
.onCreate((snapshot, context) => {
let app = admin.app();
app.database('https://flysample-75b81.firebaseio.com/').ref('/db1').set({Name:"Database1"})
app.database('https://flysample-75b81-227ae.firebaseio.com/').ref('/db1').set({Name:"Database1"})
return "done";
});
export const myFunTest2 = functions.database.instance('flysample-75b81-227ae').ref('/name')
.onCreate((snapshot, context) => {
let app = admin.app();
app.database('https://flysample-75b81.firebaseio.com/').ref('/db1').set({Name:"Database1"})
app.database('https://flysample-75b81-227ae.firebaseio.com/').ref('/db1').set({Name:"Database1"})
return "done";
});
Your code is completely ignoring the asynchronous nature of writing to the database, which means there is no guarantee that any of the database writes completes before the instance gets terminated.
To ensure the writes don't get interrupted, wait for them to complete before returning a result with something like this:
export const newTest2=functions.database.ref('/msg')
.onCreate((snapshot, context) => {
let app = admin.app();
return Promise.all([
app.database('https://flysample-75b81.firebaseio.com/').ref('/db1').set({Name:"Database1"})
app.database('https://flysample-75b81-227ae.firebaseio.com/').ref('/db1').set({Name:"Database1"})
]).then(() => {
return "done";
});
});
I have a page which requires making an HTTP request to an API which might take more than 10 seconds to respond, and my host limits me to 10 second executions.
Is there a way that I can load a temporary page or something and then asynchronously load the rest of the data? I'm currently doing this:
export async function getServerSideProps({ params }) {
const res = await fetch(`${process.env.API_USER}name=${params['name']}`)
const videos = await res.json()
const tag_res = await fetch(`${process.env.API_TAG}author=${params['name']}`)
const tags = await tag_res.json()
const name = params['name']
return {
props: { videos, tags, name }, // will be passed to the page component as props
}
}
Lets's move your HTTP request from getServerSideProps to client side (your components)
// Functional component
useEffect(() => {
fetch(...)
}, [])
// Class-based component
componentDidMount() {
fetch(...)
}
If you still want to stick with getServerSideProps, maybe you have to upgrade/switch your host, or implement a proxy/wrapper server for handling your HTTP request and return response as fast as it can