Return undefined. getStaticProps - javascript

I'm working with Next.js, I am trying accessing data but got undefined. Here is my code:
function Home({books}) {
console.log(books)
return <div>Home</div>
}
export default Home
export const getStaticProps = async () => {
let books = await getAllBooks();
return ({
props: {
books
}
}
)
}
export const getAllBooks = async() => {
const res = await axios.get("http://localhost:3000/api/v1/books", {headers: {'Access-Control-Allow-Origin': 'http://localhost:5173/'}});
if (res.status !== 200) {
return new Error("Internal Server error");
}
const data = await res.data.books;
return data
}
I am trying to fetch a data and store it in props but when I pass it in javascript component and log, it returns undefined.

What does your /pages folder look like? Do you have a v1 folder?
You are referencing "http://localhost:3000/api/v1/books" so if v1 does not exist as a folder that would be a problem unless you have some rewrite rules in place.
I used your code in a test sandbox and have no issues.

Related

getServerSideProps not fetching data despite of running it inside the page

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 } };
};

Error occurred prerendering page FetchError when i run build by next.js

I tried to build a PWA with next.js
When i run npm run dev everything works.
But when i run npm run build there are errors.
Error occurred prerendering page "/mensen/868". Read more: https://nextjs.org/docs/messages/prerender-error
FetchError: invalid json response body at https://openmensa.org/api/v2/canteens/868 reason: Unexpected token < in JSON at position 0
my file index.js from folder [id].
import { useRouter } from "next/router";
export const getStaticPaths = async () => {
const res = await fetch('https://openmensa.org/api/v2/canteens');
const data = await res.json();
const paths = data.map(mensa => {
return {
params: { id: mensa.id.toString() }
}
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch('https://openmensa.org/api/v2/canteens/' + id );
const data = await res.json();
return {
props: { mensa: data }
}
}
const Details = ({mensa}) => {
const router = useRouter();
const { id } = router.query;
console.log(id);
return (
<div>
<h1>Details</h1>
<p>{mensa.name}</p>
<p>{mensa.address}</p>
<p>{mensa.city}</p>
<p>{mensa.cordinates}</p>
<button
onClick={() => router.push(`/mensen/${id}/review/menu`)}
>Menu</button>
<p>This is the Details page</p>
</div>
);
}
export default Details;
Could someone help me to fix it.
So my idea about this project that i can call the api from website and show the details from the canteen and theirs menu.
Thank you in advance.

Sveltekit Error: `page` in `load` functions has been replaced by `url` and `params`

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

getStaticProps Does not return any data to the pages on Next.JS

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

Why I use params in getInitialProps they are undefined when build in Next.js

I have this problem in Next.js. I call the API in getInitialProps and pass the params to my components then it works when I use it in mu project. But when I want to build it gives me error that the params are undefined.
This is how I call my API and pass it to component:
import BlogItem from './blogItem'
import axios from 'axios'
import { withRouter } from 'next/router'
import { APIURL, replaceAll } from '../../../components/config'
const Post = (props) => {
return (
<BlogItem
services ={props.services }
/>
)
}
Post.getInitialProps = async ({ query }) => {
const id = query.id
const urlTitle = encodeURI(query.title)
const services = null;
try {
const response = await axios.get(`${APIURL}getservice`);
services = response.data.response.posts;
} catch (err) {
console.error(err)
}
return {
services
}
}
export default withRouter(Post)
It seems that you defined services as a const that contain null! the whole code seems fine. Try changing const to let:
Post.getInitialProps = async ({ query }) => {
const id = query.id
const urlTitle = encodeURI(query.title)
let services = null; //this line
try {
const response = await axios.get(`${APIURL}getservice`);
services = response.data.response.posts;
} catch (err) {
console.error(err)
}
console.log(services) //you should have the data right here
return {services}
}
Example :
Look at this example. Run it and navigate to /about page :
You need to make sure that your url params are passed into the querystring on the server, In your case, something like this:
server.get('/page/:uid/:id', (req, res) => {
const mergedQuery = Object.assign({}, req.query, req.params)
return app.render(req, res, '/page', mergedQuery);
})
Then your getInitialProps can get them straight from the query, regardless of where it loads.

Categories

Resources