Passing data to a server-side component in Next.js: a guide

I am working on a website dedicated to dynamic blogs and I need to pass parameters to an API URL in order to retrieve a specific blog. However, I must ensure that the approach I take does not hinder SEO by utilizing local storage, cookies, or any other client-side method. How can I effectively transmit data from one component to a server-side component?

import React from 'react'

import 'bootstrap/dist/css/bootstrap.min.css'
import "../../styles/style.css"

const fetchData = async () => {
    try {
        let slug = localStorage.getItem('auth')
        let response = await fetch(`https://sankalpitsolutions.com/ecms/api/service_info.php?slug=${slug}`)
        const backendHtmlString = await response.json()
        return backendHtmlString
    } catch (error) {
        console.log(error)
    }
}

async function displayPage(props) {
    const serviceData = await fetchData()

    return (
        <>
            <div dangerouslySetInnerHTML={{ __html: serviceData?.data?.description.replaceAll("&amp;quot;", '"').replaceAll("&amp;#39;", "'").replaceAll("amp;", "").replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll("&quot;", '"').replaceAll('className', 'class').replaceAll('classname', 'class').replaceAll('&amp;nbsp;', '') }}></div>
        </>
    )
}

export default displayPage

Answer №1

Essentially, your goal is to retrieve client-side data and transfer it to the server side.

To put it in simpler terms - you are attempting to encase something from the client side within a server component. According to NextJS documentation, this is not supported.

You likely need to create a Client Component that you will render within page - meaning you transition from importing server into client, to importing client into server (which is acceptable).

Start by creating something like ServicePage.jsx:

"use client";
import { useEffect, useState } from "react";

const ServicePage = () => {
  const [backendHtmlString, setBackendHtmlString] = useState("");

  useEffect(() => {
    const fetchHtmlString = async () => {
      try {
        const slug = localStorage.getItem("auth");
        const response = await fetch(
          `https://sankalpitsolutions.com/ecms/api/service_info.php?slug=${slug}`
        );
        const result = await response.json();
        setBackendHtmlString(
          result?.data?.description
            .replaceAll("&amp;quot;", '"')
            .replaceAll("&amp;#39;", "'")
            .replaceAll("amp;", "")
            .replaceAll("&lt;", "<")
            .replaceAll("&gt;", ">")
            .replaceAll("&quot;", '"')
            .replaceAll("className", "class")
            .replaceAll("classname", "class")
            .replaceAll("&amp;nbsp;", "")
        );
      } catch (error) {
        console.log(error);
      }
    };

    fetchHtmlString();
  }, []);

  return backendHtmlString ? (
    <>
      <div
        dangerouslySetInnerHTML={{
          __html: backendHtmlString
        }}
      ></div>
    </>
  ) : null;
};

export default ServicePage;

Then, in page.jsx, simply mount your ServicePage component:

import ServicePage from './Servicepage';

async function page(props) {    
    return <ServicePage />
}

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

Managing toggles for save and edit buttons in Vue - a comprehensive guide

I am currently working on a Vue 'app' within a larger Django application as a means to enhance my understanding of Vue. My objective is to create unique forms that can be edited independently. I have been experimenting with this for some time n ...

What is the solution for handling nested promises in Node.js?

I am currently using the node-fetch module for making API calls. I have a function that handles all the API requests and returns both the status code and the response body. The issue I'm facing is that when returning an object with the response data, ...

What is the best way to pass an object into a method within a select element using Vue

Kindly review the following code snippet. <tr> <td>Select Timeslot</td> <td colspan="2"> <select class="form-control" v-on:change="onTimeSlotClick"> <option v-for="slot of slots"> <l ...

What is the best way to save the content of an RFC822 message body as a String?

let inbox = require("inbox"); let client = inbox.createConnection(false, "imap.gmail.com", { secureConnection: true, auth:{ user: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99f4e0fcf4f8f0f5d9fef4f8f0f5b7fa ...

Several jQuery ajax requests seem to be failing due to errors in previous calls

I am experiencing an issue with my website's login form that utilizes ajax to send the login information to php. After successfully logging in, users have the ability to log out and then return to the login page again. However, I am facing a problem w ...

Analyzing the differences in environment management between express and dotenv

Lately, I've noticed an abundance of tutorials and articles discussing NodeJS and the dotenv library. One common practice that keeps coming up is defining an ENV_MODE=development variable within the config.env file. However, it got me thinking - does ...

Developing Your Own Local Variable in Angular with Custom Structural Directive ngForIn

I am hoping for a clear understanding of this situation. To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below: import {Directive, Input, OnChanges, SimpleChan ...

Having difficulty receiving a response from an AJAX call within the success function

After browsing through this stack link Ajax response not calling success:function() when using jQuery 1.8.3, I'm puzzled as to why the success function is not invoked when I uncomment the dataType line. It seems that setting dataType = JSON prevents t ...

The declaration file for module 'react-scroll-to-bottom' appears to be missing

I recently added react-scroll-to-bottom to my project and it is listed in my dependencies. However, I am encountering the following error: Could not find a declaration file for module 'react-scroll-to-bottom'. The path 'c:/Users/J/Desktop/w ...

A guide on navigating through nested JSON objects with the help of async.js

Having recently transitioned from a Python background to nodeJS/Javascript's asynchronous nature, I am exploring how to traverse a nested JSON object and extract its values using async.js. In my quest for answers, I stumbled upon this helpful snippet ...

A guide on invoking a Struts 2 action with a different parameter for each row in a jQuery DataTable

Currently, I am working on a JAVAEE project that involves the use of Struts 2 and jQuery DataTable. In this project, I need to add a link with each row in the DataTable that will call an action based on the row's ID. Below is the HTML code for this s ...

Adjust the height for just one md-tab

Looking to find a way to set the height of the content within an <md-tab> element to be 100% in a flexible manner. For example, consider the following structure: <body> <md-content> <md-tabs> <md-tab label= ...

Firestore is failing to accept incoming data when the setDoc method is employed

I am encountering an issue with my app's connectivity to the Firestore database when attempting to utilize setDoc. The database is successfully operational for next-auth, creating records as intended. However, the problem arises when trying to enable ...

What causes material-ui styling to flicker while moving between pages in Next.js?

Visit this link for more information Experience a unique button styling transition when moving from one page to another. Check out the code snippet here: Explore the code on GitHub ...

The tooltip for the Google+ button stopped working

After setting up my Portfolio, I added a Google+ button. However, the page lacks styling and there seems to be an issue with the tooltip causing delays. Can anyone help me identify where the problem lies? ...

Guide on getting a website name from a URL using Javascript

Is there a simple method to extract the site name from a URL string? For example: http://www.mysite.com/mypath/mypage -> www.mysite.com http://mysite.com/mypath/mypage -> mysite.com The JavaScript code runs on the mongodb CLI side, not within ...

Move tables by dragging and dropping them into place

Currently, I am on the lookout for a drag and drop plugin that works with jQuery, Angular, or JavaScript to help me create dynamic tables. Specifically, I need a plugin that allows me to add new tables through drag and drop functionality. While I have com ...

The integration of Angular 6 with AngularJS components fails to load properly in a hybrid application

Currently, I am in the process of upgrading a large AngularJS version 1.7.3 to a hybrid app using Angular 6. The initial phase involved converting all controllers/directives into an AngularJS component. Subsequently, I created a new Angular 6 project skele ...

Alternating the tooltip icon based on the field's condition

Looking for a way to create a tooltip for an input field that involves changing icons based on certain conditions. An example scenario is the password field in a registration form. Seeking advice on the best approach to achieve this. Currently, here' ...

I'm noticing that my Tailwind styles don't take effect until I redefine them. What could be causing

My Tailwind classes are giving me trouble. I faced an issue when I created a new component in the directory and placed my Button component there. Whenever I restart the project in terminal, the styles do not apply to my button unless I manually define th ...