The benefits of NEXTJS Server Side Rendering include providing clear and defined content

Even though I've followed the solution provided above for fetching data, I still end up receiving 'undefined' instead of the actual data. Interestingly, when I make the same request using Postman or Thunderclient, it returns a success with status code 200. Can anyone offer some assistance?...

export async function getServerSideProps(context) {

    const res = await fetch('http://localhost:5000/api/blogpost/view');
    const { data } = await res.json();
    return {
      props: {
          blog: data,
        },
    }
  }
const Page = ({blog}) => {
    console.log({ blog: blog, title: "nothing" });
    return (
        <div><h1>Hello</h3></div>
 )}

export default Page;

**I have also attempted to wrap the fetch request inside a try-catch block, but I still encounter the same issue of receiving 'undefined' **

export async function getServerSideProps(context) {
  // Fetch data from external API
  try {
    const res = await fetch('http://localhost:5000/api/blogpost/view');
    const { data } = await res.json();
  } catch (error) {
    console.log(error);
  }
  console.log(data);

  // Pass data to the page via props
  return { props: { blog: data } };
}

The console output remains the same as previously received

{ blog: undefined, title: 'nothing' }

Answer №1

One potential issue may be that your api is missing the "data" object. Consider modifying "const {data}" to simply "const data". It might also be beneficial to provide a sample response from your api for further investigation.

export async function getServerSideProps(context) {

const res = await fetch(`http://localhost:5000/api/blogpost/view`);
const  data  = await res.json();
return {
  props: {
      blog: data,
    },
}
 }
const Page = ({blog}) => {
console.log({ blog: blog, title: "nothing" });
return (
    <div><h1>Hello</h3></div>
)}

export default Page;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Material UI tabs panel with customized CSS styling

Having trouble changing colors and CSS in the TAB PANEL using material-ui. Any tips or suggestions? :( It seems like useStyle and theme functions are not working as expected. I was able to modify other properties like scrollable, but colors seem to be fix ...

The functionality of the "Slots" prop has no impact when used on the material-ui Slider component

Trying to understand the purpose of the "slots" prop in relation to customizing how inner components like track and thumb are rendered within the Slider component. A basic example of rendering a Slider component is shown below const marks = [ { value: 0 ...

What is the process of manually loading webpack async chunks in the event that a dynamic import fails to load the file?

Async chunks in webpack can be created by using Dynamic Imports (for example: import('./ModuleA.js');). If the dynamic chunks fail to load, I want to retry loading them from another location. After grappling with the issue and delving into babel ...

having difficulty utilizing svg files in a react application

I'm having trouble with a SVG image. I initially tried importing it from a folder, but it appeared empty. Then, I attempted to directly specify the path, but that didn't solve the issue. The file name is image.svg <svg xmlns="http://www. ...

Is there a method to consistently keep the horizontal scrollbar in view for the MUI Data Grid at all times?

I have a Data table with virtualized columns, totaling more than 25 in number. Users can easily scroll horizontally using a trackpad, but without one, they may struggle to access all the columns due to the delayed appearance of the scrollbar. Is there a w ...

What is the method to individually determine "true" or "false" using .map() in coding

I am faced with an array of data that needs to be manipulated individually, but it should still function as a cohesive unit. Can you assist me in achieving this? function OrganizeFollow() { const [followStatus, setFollowStatus] = useState([]); co ...

The initial value for Redux-thunk input

I have created a simplistic Single Page Application (SPA) using the thunk library. This application utilizes the GitHub API to fetch a list of repositories. Initially, I had implemented an example with a class-based presentational component that included l ...

What is the process for updating field values when opening the modal with various modes and input values?

Encountering an issue with the Modal Form component where the fields do not update when opening the modal in different modes with initial values. Despite attempting to pass initial values into Antd Form, the expected behavior is not achieved as the field v ...

Issue with Circular Progress not reflecting Material-UI-next Theme

After following the documentation, I updated my theme but the circular progress element still displays the default primary color instead of the one specified in the theme. My goal is to enable end users to adjust the theme using mobx computed values, but e ...

What is the best way to center my items vertically in a material-UI Grid row?

Struggling to vertically align three items in a row using Material UI's Grid component. Despite setting "justifyContent: 'center'," it only horizontally centers the items. Here are my styles: const styles = (theme) => ({ root: { te ...

What causes the variation in output results between axios and express when using dot notation?

A geo tool application is in the works, built with reactjs. The concept involves users submitting a city name which then triggers a post request. This request searches through a city list.JSON file to find the corresponding city and returns its geolocation ...

Having trouble rendering Next.JS dynamic pages using router.push()? Find out how to fix routing issues in your

The issue I am facing revolves around the visibility of the navbar component when using route.push(). It appears that the navbar is not showing up on the page, while the rest of the content including the footer is displayed. My goal is to navigate to a dy ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

Incorporate an Application Bar into the table

I'm seeking assistance with incorporating a new component into my table using React JS. While this task may be simple for those experienced with the platform, I am encountering some difficulties. The table in question is sourced from Material UI and ...

The notifications for events on Google Calendar are not being received by attendees' Gmail inboxes

I've been utilizing the Google Calendar API to insert events into Google Calendar. While the events are being added to attendees' calendars, I'm facing an issue where the notification of event creation is not showing up for both the attendee ...

Tips for avoiding accidentally selecting nearby text while holding down a button on your mobile device

My application requires the user to press and hold a button to record audio. However, on mobile devices, when the user holds the button, the browser attempts to select nearby text due to finger pressure. While this behavior is understandable, I want to pre ...

Exploring the World of Card Components in ReactJS

Error: Encountered an Error: TypeError - Unable to read property 'card' of undefined. Removing the content className={classes.card} resolves the issue. However, without classes, Const Styles cannot be utilized. import React from 'r ...

Comparing two inherited classes in Typescript: A step-by-step guide

Let's say we have two classes: Animal and Dog. The Dog class is a subclass of the Animal class. I am trying to determine the types of these objects. How can I accomplish this task? class Animal {} class Dog extends Animal {} //The object can be of ...

What is the best way to create a div that extends beyond the borders of the screen, but still allows only

I am currently working on a React project for a website. I am creating a category bar that should slide only the component in the mobile version, without moving the entire page. Check out the desired design here However, the current appearance is differe ...

Having trouble setting the `variant='dense'` for material-ui Toolbar – it remains at a height of 64px no matter what

Implemented a hello world AppBar/Toolbar with the variant='dense' style. import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import registerServiceWorker from './registerServiceWo ...