Encountering a Next.js application error while utilizing the button tag in conjunction with generating metadata

I keep encountering an issue with generateMetaData when trying to utilize the button tag. Can you help me resolve this problem?

Currently, I am working with nextjs and I am unable to properly use the <button> tag.

Whenever I implement generateMetaData provided by nextjs, I receive the error message "Application error: a client-side exception has occurred (see the browser console for more information)."

This is how I define my generateMetaData code:

const getArticle = cache((id) => {
  const articleService = new ArticleService();
  return articleService.getOne(id).then((res) => {
    return res.resultFinal;
  });
});

export async function generateMetadata({ params }) {
  const id = params.id;
  const articleService = new ArticleService();

  const article = await articleService.getOne(id).then((res) => {
    return res.resultFinal;
  });

  if (!article) {
    return {
      title: "Article not found",
      description: "Article not found",
      openGraph: {
        title: "Article not found",
        description: "Article not found",
      },
    };
  }

  return {
    title: article.title,
    description: article.description,
    openGraph: {
      title: article.title,
      description: article.description,
      images: [process.env.NEXT_PUBLIC_IMAGE_BASE_URL + "/" + article.medias[0].url],
    },
  };
}

Here is a snippet of my component:

export default async function Page({ params, searchParams }) {
  const article = await getArticle(params.id);

  const sharedFacebook = async () => {
    alert("clicked");
  };

   return (
      <>
      <button onClick={sharedFacebook}></button>
      </>
    )
}

Adding "use client" in the sharedFacebook function seems to work, but clicking the button still triggers the "Application error..." message:

The same issue occurs when I add "use client" at the beginning of my component.

Answer №1

Page acts as a Server Component while <button> functions as a Client Component [1]. The function sharedFacebook is non-serializable, meaning only serializable props can be passed from Server Components to Client Components.

To resolve this issue, you must transfer the event handler sharedFacebook to a Client Component.

// app/page.tsx

import {Button} from "./button";

export default async function Page({ params, searchParams }) {
  const article = await getArticle(params.id);

   return (
      <>
        <Button />
      </>
    )
}
// app/button.tsx
"use client";

export function Button() {
  const onClick = () => {
    console.log("clicked!")
  }

  retrun <button onClick={handler}>Click Me</button>
}

  • [1] Essentially, every html built-in element serves as a client component since the browser alone understands how to interact with them.

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

Run Javascript code if a specific CSS class is present on an element

Whenever a user enters an incorrect value into a textbox on my page, an error message is displayed within a div with the class 'validation-errors'. I'm looking for a solution to trigger a javascript function (which adds a CSS property to a ...

A method to find the sum of the final n elements in an array by employing Arr.reduceRight

I have successfully calculated the sum of the last n elements in an array using a for loop. Is it possible to achieve the same result using Arr.reduceRight instead? x = [1,2,3,4,5]; y = 0 for(let i=x.length; i>x.length-3; i--) { console.log(x[i-1]); ...

How to arrange elements at the same level in Node.js using sequelize-hierarchy?

Is there a way to change the order of items on the same level in sequelize-hierarchy for creating a menu? I've noticed that currently, the items are ordered by their sequence of insertion. But what if I want to manually set the order? Here is an exam ...

Slider-activated Pie Chart Controller

I have successfully created a pie chart using highchart and javascript, allowing me to adjust each slice individually using a slider. However, I am facing an issue where I want the maximum value of the pie to be 100%, with the other sliders contributing to ...

ReactJS Material-UI Tooltip and Popper overlapping issue

How can I make the MUI tooltip appear beneath the MUI Popper, with the popper overlapping the tooltip? Is there a way to modify the z-index for only a specific portion of the elements without affecting the global styles when using external CSS? Here is a ...

Pause the for loop until all nested asynchronous database calls are completed

Currently, I am utilizing the listCollection method within mongodb to loop through each collection that is returned using a query with find. The issue arises when I attempt to construct an object within the loop that I intend to return with response.json ...

Tips for getting information from a GET/POST response message with superagent

I'm currently utilizing Node.js and Superagent for testing my server implementation. I have successfully sent a Superagent GET request and received a positive response with the code provided below. My goal is to extract and log only the "id" value fro ...

What are the steps to create offline documentation for sails.js?

I am looking to integrate offline sails.js documentation into my system. You can find the official documentation for sails.js maintained at this Sails.js Documentation. According to their documentation, they use doc-templater for building the documentati ...

Error code received from OpenStack Identity API GET response

I am an intern student and I have a query. Currently, I am working on bug fixing for an Openstack cloud, JavaScript, and Node.js web application. My task involves resolving toastr.error messages and translating them into different languages. How do I ret ...

What is the significance of the error message "Uncaught (in promise) Object"?

I am facing an error in my code and need help to correct and debug it. I would like the code execution to halt when an issue arises. Here is my code snippet: export function postRequestOtpCode(phone: string, token: string): CancellableAxiosPromise { ax ...

React Router isn't displaying any content

I'm facing an issue with react-router-dom where none of my components are rendering and I just see a blank white screen. The content is not being added to my index.html template, even though there are no visible errors. Interestingly, it mentions that ...

"Unexpected Type Inference Issue: A variable initially defined as a string inexplicably transforms into 'undefined'

Currently, I am incorporating the await-to-js library for handling errors (specifically utilizing the to method from the library). In an intriguing scenario, the variable type shifts to string | undefined within a for..of loop, whereas outside of the loop ...

Having difficulty importing the WebRTCAdaptor from the antmedia package stored in the node modules directory into an Angular Typescript file

An error is appearing indicating that: There seems to be a problem finding a declaration file for the module '@antmedia/webrtc_adaptor/js/webrtc_adaptor.js'. The file 'D:/web/node_modules/@antmedia/webrtc_adaptor/js/webrtc_adaptor.js' ...

Certain iFrame instances are unable to display specific cross-domain pages

I'm currently working on a project to create a website that can embed external cross-domain sites, essentially like building a browser within a browser. I've been experimenting with using iFrames for this purpose: While it works for some pages, ...

Show the user's chosen name in place of their actual identity during a chat

I'm facing an issue where I want to show the user's friendly name in a conversation, but it looks like the Message resource only returns the identity string as the message author. I attempted to retrieve the conversation participants, generate a ...

What is the reason behind being limited to sending only 5 requests if I fail to heed the data event?

I've come across some related questions while researching this topic, such as Why is node.js only processing six requests at a time?. However, I am still struggling to fully grasp the specifics. Below is a breakdown of my scenario: Firstly, let&apos ...

Adjust fancybox height using jQuery

I am working on a project where I need to display a fancybox containing an iframe from another domain. The iframe has dynamic content and its height may change based on the pages it navigates to or the content it displays. I have access to the code of the ...

Unable to get the code for automatically refreshing a DIV every 5 seconds to function properly

My Inquiry Regarding DIV Refresh I am having issues with the code below that is supposed to automatically refresh the DIV id refreshDiv every 5 seconds, but it is not working as expected. <div id ="refreshDiv" class="span2" style="text-align:left;"&g ...

An error occurred when attempting to set state within a nested fetch

Having difficulty solving an issue with react.js. loadFromServer(pageSize) { fetch('http://localhost:8080/api/employees') .then(response => { return fetch('http://localhost:8080/api/profile/employees', ...

An unexpected error has occurred in the browser console: The character '@' is not valid

I recently made the decision to dive into learning about Unit Testing with JavaScript. To aid in this process, I started using both Mocha.js and Chai.js frameworks. I downloaded the latest versions of these frameworks onto my index.html from cdnjs.com. How ...