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

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.

Related

Dynamically import a module Next.js, but with server side rendering

I have a [...pageId].tsx file in the /pages directory.
In getServerSideProps, the page will check a CMS, and find a list of components to render. I want to load those components serverside, then render them out, then return the page.
Using next/dynamic like below will load the components, but it will not render them serverside. They will only stream in on the client. In other words: the customer will see 'Loading...' first, then the component renders. That's not what I want, also not for SEO.
const getDynamicComponent = (c) => dynamic(() => import(`../../components/${c}`), {
loading: () => <section>Loading...</section>,
ssr: true
});
export default function SomePage({page}) {
// Load dynamic component if necessary
let DynamicComponent = getDynamicComponent(page.reactComponent);
}
return (
<DynamicComponent page={page} />
)
}
How can I achieve serverside rendering using dynamic imports?

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

How to retrieve some data from API and use it in all the pages of a NexJS application before rendering on client side?

I have a NextJS application where I have a home page (index.js) and two other pages About(about.js) & Contact Us(contact.js).
I have created a BaseLayour.js file with is wrapping NextJS's MyApp component in _app.js file.
import React from "react";
import BaseLayout from "../layouts/BaseLayout";
function MyApp(props) {
const { Component, pageProps } = props;
return (
<BaseLayout>
<Component {...pageProps} />
</BaseLayout>
);
}
export default MyApp;
This BaseLayout component looks like this -
import React from "react";
import SEO from "../components/SEO";
import Header from "../components/Header";
import Footer from "../components/Footer";
function BaseLayout(props) {
const { children } = props;
return (
<div>
<SEO />
<Header />
{children}
<Footer />
</div>
);
}
export default BaseLayout;
As you can see above in the BaseLayout file, there is an SEO component (React). It contains some common metadata for all the pages. I have an API(api/getmetadata/) that delivers all the metadata in JSON format.
This metadata is supposed to load on the server-side so that the page will be optimized for SEO.
How can we call the API in order to retrieve the data on each request but only on the server-side?
What I have tried till now -
Tried calling API in the SEO component itself, but it is not running on the server-side as it is just a React component.
Tried creating a React context, and called the API from SEO/BaseLayout components, the API call is still not being made from the server-side.
Tried using getServerSideProps in the index.js page to call the API and retrieve the data, which worked perfectly, but the problem is we need to share the data between all the pages, not just the index.js home page.
Any help will be appreciated, If we can somehow make the API call and retrieve the data in the SEO component, it will solve our problem.
Thank you in advance guys.

axios request getting blocked | Reactjs

I am trying to hit an endpoint in my reactjs code using axios but the request is getting blocked and I am getting the following error in my console.
Please suggest how to overcome this
Below is my code
import * as React from 'react';
import axios from "axios"
export default function App()
{
return (
<>
<button onClick={fetchdata}>Click Me</button>
</>
)
}
function fetchdata()
{
const axios = require('axios');
// Make a request for a user with a given ID
return axios.get('https://randomuser.me/api')
.then(response => {
// handle success
console.log(response);
return response;
})
.catch(error => {
// handle error
console.log(error);
})
}
The reason you're getting this error is because https://randomuser.me expects request from secured origin using https protocol and localhost by default does not runs over https. If this is not satisfied it will be returned as a warning/error by your browser.
However, if you have generated React Project using create-react-app then you can add following script in your package.json:
"proxy": "https://randomuser.me"
Please refer document of Create React App for more details.
It's working fine, please check here
Codesandbox: https://codesandbox.io/s/muddy-dust-yvotv?file=/src/App.js
sometimes this error coming because you started any plugin/extention of cors in your browser

Categories