getStaticProps returning empthy object - javascript

on IndexPage i am calling an api using getStaticProps. when i console.log this on frontend i get an empty object on the browser.
iam using NextJS
const IndexPage = (props) => {
console.log(props)
return(
<h1>Hello</h1>
)
}
export async function getStaticProps() {
const res = await fetch("https://jsonplaceholder.typicode.com/todos");
const posts = await res.json();
return {
props: {
posts,
},
};
}
export default IndexPage;

Did not play around with it, but I'm almost sure that if you view console output of you console where you started nextjs app you will see results there, take a look please. Here is explanation from documentation:
If you export an async function called getStaticProps from a page, Next.js will pre-render this page at build time using the props returned by getStaticProps.
The key part here will pre-render at build time. So getStaticProps will be called on the server side during server side rendering.

Related

Fetch-request from React frontend doesnt work

I am making a simple program with a backend in ASP.NET Core Web API, and a frontend in JS React. I have a SQL-database in my backend with a table called Events (Arrangementer in Norwegian). The events table has three columns: ID, name, and description.
I have opened and started the react-project. In my App.js (which is the only file I have edited since opening the project), I am trying to fetch some event data from my SQL-database. When I try to console.log() the json-response, nothing gets outputted to the console. I have tried using an ASYNC function, but that doesnt work either. My backend is up and running, and I have data inside of the tables, i can see that when i click the fetch-url.
Here is the App.js file:
import logo from './logo.svg';
import './App.css';
import {useEffect, useState} from 'react'
function App() {
useEffect(() => {
fetch("https://localhost:7031/api/Arrangements")
.then((res) => res.json())
.then((json) => {
console.log(json)
})
}, [])
return (
<div className="App">
<header className="App-header">
testing project
</header>
</div>
);
}
export default App;
The getter in the Swagger UI
I believe something is wrong with the endpoint. First thing that strikes me is that the url you are using starts with https:// but adresses localhost. I'm aware that's possible, but are you sure it's not http:// ?
To be sure of that, please test your endpoint using Postman or the Chrome Dev tools network tab - both should give you sufficient information about the status of your endpoint.
Your frontend code looks good and should work, so I believe you have a backend problem.
Try it plz. Seems your code is fine. If your get response from Backhand(200 in Network Tab) no issues.
import React from 'react';
import { useState,useEffect } from 'react';
const MyApp = () => {
const [service, setService] = useState({})/According to Your API response;
useEffect(() => {
const url = "http://localhost:7031/api/Arrangements";
fetch(url)
.then(res =>res.json())
.then(data => setService(data));
}, [])
return (
<div>
<p>{service.length}</p>
</div>
);
};
export default MyApp;
If you console log the res, you will see some response.
But I don't think you can use JSON in the last .then, because res.json() doesn't save your data anywhere.
Try using a useState, and set that state in the last .then.

I am trying to create dynamic routes in NextJs. I am using .map to render the page list and am having trouble wiring it together

I am using NextJs and want to create dynamic routes for different projects. I am having trouble getting the list page to render properly. I plan on eventually moving to Postgres but in dev I am using JSON files in the public folder for the time being. I am attempting to use the .map method to render the data from a json file and can not get it running properly. Inside the pages folder I have a project folder which contains an index.js that looks like this.
'''
export default function ProjectList() {
return <h1>Project List</h1>
}
,,,
As well as an [id].js file like this
'''
import { useRouter } from 'next/router'
export default function Project({ project }) {
const router = useRouter()
const { id } = router.query
return (
{project.map(({title, subtitle, image, logo, description}) => (
<div className="Project-Faucets">
<div className="Project-Title">{title}</div>
<div className="Project-Subtext">{subtitle}</div>
<img src={image} alt='visual' className="Project-Image" />
<img src={logo} alt='visual' className="Project-Logo" />
<div className="Project-Content">{description}</div>
</div>
))}
)
}
export async function getServerSideProps({ params }) {
const req = await fetch(`http://localhost:3000/${params.id}.json`);
const data = await req.json();
return {
props: { project: data },
}
};
'''
I have been playing with several different attempts but am having no luck and although I may be wrong I am thinking the .map method may be the cause of my problem. Any help or guidance would be appreciated! After typing this I started thinking it may have to do with my json files not being an array ...... Ill look into that now

SWR not returning any data

I'm trying to get SWR to work. Every example I have found doesn't seem to work when i apply it to my code. I'm not sure what i'm doing wrong the code appears to be the same, i'm sure something super simple that i just can't see.
I have a boilerplate next.js app.
my index.js has;
import useSWR from 'swr'
export default function Home({ isConnected }) {
const { data, error } = useSWR('/api/')
return() //jsx here
}
when i start the development server up it tells me http://localhost:3000 is where the development server can be viewed. when i debug and pause in the on the return line it tells me that data and error are undefined. when i go to http://localhost:3000/api/ i get well formed json back(firefox renders it as json).
You need a method to make the request, for you case, it could be like:
import useSWR from 'swr'
import axios from 'axios';
export default function Home({ isConnected }) {
const fetcher = async () => {
return await axios.get('http://mipage/some/');
};
const { data, error } = useSWR('/api/', fetcher)
return() //jsx here
}

How to programmatically navigate to other page in Next.js?

After a post request to an external API, I would like to redirect back to the homepage. I do have some knowledge with React and this is my first time using Next.js. Here is the code:
export default function New({genres}) {
const createMovie = (values) => {
console.log(values);
axios.post(`${process.env.NEXT_PUBLIC_BASE_URL}/movies`, {
title: values.title,
description: values.description,
genres: values.genres,
release_date: values.release_date,
cover_url: values.cover_url
}).then(res => {
const router = useRouter();
router.push('/');
})
}
As you can see I used router.push() but I get this error:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
What is the most efficient way to redirect to other pages in Next.js after a function and/or requests?
You need to move where you call useRouter(). You can keep router.push() where it is.
export default function New({genres}) {
const router = useRouter();
const createMovie = (values) => {...}
}
If you look at the Rules of Hooks, you can only call the hook, useRouter() in this case, at the top level.
I also had my initialization of useRouter in my function. I fixed the same bug by placing that line into my function component instead of my function and calling router.push(...) in the function itself.

Next.js hangs while setting initial props on server-side

I am trying to set up SSR with Nextjs.
I have following code, where I am fetching json data and binding them as initial props.
When I am in development mode all works correctly, when I deploy to the server fetching works only on client-side (when I navigate from other view).
If I try to load directly the page with fetching, server hangs, no error.
I should add that all is running inside Docker container, but I guess it should not matter at this case.
Here is code
import React from 'react'
import { get } from 'axios'
import Layout from '../components/Layout/Layout'
import WorkSingle from '../components/Work/WorkSingle/WorkSingle'
import DocumentTitle from '../hoc/DocumentTitle/DocumentTitle'
const Work = (props) => {
let works = 'Loading...'
if (props.workData.length > 0)
works = props.workData.map(work => (
<WorkSingle
img={work.image}
url={work.url}
title={work.title}
key={work.title}
/>
))
return (
<Layout>
<DocumentTitle title='Some page title' />
<section id="work">
<h1 className="font_title">WORK</h1>
<div className="row">
{works}
</div>
</section>
</Layout>
)
}
Work.getInitialProps = async () => {
const response = await get('VALID_URL')
if (response && response.data)
return { workData: response.data.work }
return {}
}
export default Work
I have solved it, problem was that i wanted to fetch static data from the same server which is serving app, for some reason when server tried to fetch from itself it stuck, I put the resource I am fetching to another server for now and it solved problem.
I was mocking the data via static .json file, I guess when I create actual API endpoint it will work from the same server too.

Categories