When I'm using getServerSideProps with next js and it almost takes 5 or 6 seconds for the page to load . I tried using only one url to fetch and not many but again it takes alot for the page to load .
export const getServerSideProps = async (ctx) => {
let data ;
try {
data = axios.get("url")
} catch(e){
data = "error"
}
return {
data: data,
};
};
I was wondering is there any trick to speed up getServerSideProps data fetching so I could have faster initial page load ?
got this solution while searching for this bug
const isServerReq = req => !req.url.startsWith('/_next');
function Post({ post }) {
// Render post...
}
export async function getServerSideProps({ req }) {
const initData = isServerReq(req) ? await fetch(...) : null;
return {
props: {
initData,
},
}
}
issue: https://github.com/vercel/next.js/issues/13910
Related
hello i am trying to fetch data inside by next app using getServerSideProps which is just not fetching the data , the data returns either an empty object or undefined inside the console i don't know what is wrong with the app , i have tried other next js data-fetching methods too and results are same
export const getServerSideProps = async () => {
// Fetch data from external API
const res = await fetch(`https://rickandmortyapi.com/api/character`)
const data = await res.json()
console.log(data)
// Pass data to the page via props
return { props: { data } }
}
I threw that code into my current project and it works.
interface Props {
data: {
info: any;
results: any[];
}
}
const Page: NextPage<Props> = ({ data }) => {
console.log(data); // { info: {...}, results: Array(20)}
// ...
}
export const getServerSideProps = async () => {
const res = await fetch('https://rickandmortyapi.com/api/character');
const data = await res.json();
return { props: { data } };
};
I'm trying to understand the main difference between getServerSideProps and just using useSWR inside of the page component. If I run something like this inside getServerSideProps:
export const getServerSideProps = async () => {
try {
const palettes = []
const docRef = query(collection(db, 'palettes'), orderBy('likes', 'desc'), limit(16))
const docData = await getDocs(docRef)
docData.forEach((doc) => {
palettes.push(doc.data())
})
if (!docData) {
return {
props: {
data: { error: 'Failed to load palettes. Please refresh the page.'}
}
}
} else {
return {
props: {
data: { palettes }
}
}
}
} catch (e) {
console.log('error:', e)
}
}
It will run at build time and then on each request by the user when viewing/navigating to the page?
Then what would be the difference from just using useSWR or another API fetcher like:
export default function PaletteSlugs({ slug }) {
const { data, error } = useSWR(`/api/palette/${slug}`, fetcher)
return (
{data}
)
}
Also could this affect how many request/reads will happen on the database?
Simply, using getServerSideProps will get the API data on the Node.js server, while the HTML page will be completely populated by Node.js on the server. If you try to open the page source in the browser you will see all data already exists in the page source, this will be better for SEO.
But with useSWR will get the data on the client-side like normal fetch and the data will be populated on the client-side.
I am trying to display my date from GraphCMS in my blog application. I receive this error when I go to my single post link (http://localhost:3000/posts/union-types-and-sortable-relations)
"
page in load functions has been replaced by url and params
Error: page in load functions has been replaced by url and params
"
Here is my code
<script context='module'>
export const load = async ({fetch, page: {params}}) => {
const {slug} = params
const res = await fetch(`/posts/${slug}.json`)
if(res.ok) {
const {post} = await res.json()
return {
props: {post},
}
}
}
</script>
<script>
export let post
</script>
<svelte:head>
<title>Emrah's Blog | Welcome</title>
</svelte:head>
<pre>{JSON.stringify(post, null, 2)}</pre>
Can you please help. Thanks
Try using params instead of page: params, though the latter still works in Sveltekit 278 (which I'm using).
Besides, I'm curious to know what makes you prefer this method to querying GraphCMS for your single post. I do it like this:
import {client} from '$lib/js/graphql-client'
import {projectQuery} from '$lib/js/graphql-queries'
export const load = async ({ params }) => {
const {slug} = params
const variables = {slug}
const {project} = await client.request(projectQuery, variables)
return {
props: {
project
}
}
}
Yes, this has been changed a while ago, now the different parts of what used to be page are passed directly into the load function:
export async function load({ fetch, page }) {
const { params, url } = page
}
export async function load({ fetch, params, url }) {
}
Something else to consider is that now there are page endpoints, if your file is [slug].svelte you can make a file [slug].js and add the following:
export async function get({ params }) {
const { slug } = params;
const post = {}; // add the code to fetch from GraphCMS here
return {
status: 200,
body: {
post
}
}
}
With this you can remove the load function and make your code simpler (especially because you technically already have all this code in your /posts/[slug].json.js file.
<script context='module'>
export async function load({ fetch, params}){
let id = params.users
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`)
const user = await response.json()
if(response.ok){
return {props:{user}}
}
return {
status: response.status,
error : new Error(" sorry no user found")
}
}
export let user
I'm trying to fetch a data from my hosted database. The database itself are working (I have checked it from the swagger app) but no data is shown when it is called from API form.
import React from 'react';
export const getStaticPaths = async () => {
const res = await fetch('https://[server]/course');
const data = await res.json();
const paths = data.result.map(course => {
return {
params: { id: course._id.toString() }
}
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch('https://[server]/course/' + id);
const data = await res.json();
return {
props: { course: data }
}
}
const Details = ({ course }) => {
return (
<div>
<h1> { course.course_name } </h1>
<h1>a</h1>
</div>
);
}
export default Details;
The code is in the pages folder. I followed a tutorial on youtube from "netninja" and when I tried it on his code it works. I read somewhere that it won't work on components but I already put it on the pages but it still does not return anything.
Is there anything I can do ?
I got the answer. After checking console.log on the data. Looks like the data is on another array which is called result. so i needed to call the data from course.result.course_name. So the Answer is just to check console.log every once in a while. Shout out to juliomalves for pointing that out
I am integrating paytm payment gateway in my nuxt js project. Buy I am
unable to get post data with which paytm is redirecting to my callback
url.
Since asyncData gives you access to req and res (see https://nuxtjs.org/guide/async-data/#use-reqres-objects), you can parse the body to get POST parameters. I found this solution out there, so I didn't try it out. In fact, it should be better to use a Middleware to parse this and load the middleware in that page.
<script>
export default {
asyncData ({ req, res }) {
if (process.server) {
const qs = require('querystring')
let body = ''
let temp = ''
let paymentData = ''
while(temp = req.read()) {
body += temp
}
paymentData = qs.parse(body)
return { data: paymentData }
}
},
data () {
return {
paymentData: '',
}
},
mounted () {
console.log(this.paymentData)
}
</script>