How can I update getServerSideProps using a change event in Next.js?

Currently, I am faced with the task of updating product data based on different categories. In order to achieve this, I have set up an index page along with two components called Products and Categories. Initially, I retrieve all products using the getServerSideProps method, but my goal is to fetch products specific to a selected category once the user chooses one.

Index Page

import Link from 'next/link';
import Layout from '../components/layouts/App';
import Products from '../components/Products';
import Categories from '../components/Categories';
class Index extends React.Component {
    state={
        products:this.props.products,
    }
    
//receiving category id and trying to change state products
    catProducts = async (cat_id) => {
        const res =  await fetch(`https://example.com/get_products?api_key=4e38d8be3269aa17280d0468b89caa4c7d39a699&category_id=${cat_id}`, { method: 'GET' })
        const productsdata =await res.json()    
        console.log(productsdata)
        // this.setState({products: productsdata})
    }

    render() {
        
        return (
            <div>
                <Layout>
                    <div className="main-wrapper pt-35">
                        <div className="row">
                            <div className="col-lg-3">
                                <Categories categories={this.props.categories} catchange={this.catProducts}/>
                            </div>
                            <div className="col-lg-9 order-first order-lg-last">
                                <Products  products={this.state.products} />
                            </div>
                        </div>
                    </div>

                </Layout>
            </div>
        )
    }


}





export async function getServerSideProps() {
    const cats_req = await fetch('https://example.com/api/get_categories?api_key=4e38d8be3269aa17280d0468b89caa4c7d39a699', { method: 'POST' })
    const categories = await cats_req.json();
    const products_req = await fetch(`https://example.com/api/get_products?api_key=4e38d8be3269aa17280d0468b89caa4c7d39a699`, { method: 'GET' })
    const products = await products_req.json();

    return {
        props: {
            products: products,
            categories: categories
        }
    }

}




export default Index

A challenge arises as I encounter the error message:

Unhandled Runtime Error TypeError: Failed to fetch

Given that I am relatively new to Next.js, any guidance or suggestions on how to address this issue would be greatly appreciated.

Answer №1

Are you receiving the desired data when using the getServerSideProps function?

I noticed that in catProducts, the URL does not contain '/api', whereas in getServerSideProps it does. This difference could be a possible reason.

Additionally, please ensure to handle promises properly when using fetch.

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

Ways to conceal a parameter in Angularjs while functioning within the ng-bind directive

I am using Angular to create the final URL by inputting offer information. Below is the code snippet: <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> ...

A more intelligent approach for generating JSON responses using Mysql

Here is the code I have on my server side using Node.js: var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'SOMEUSER', password: 'SOMEPASSWD', database: 'SOMED ...

How to access the dynamic route's path in Next.js when using Server Components?

Obtaining the dynamic route path in a Next JS server component poses a challenge. This task is simple when working with client components. If you are working on src/app/[id]/page.tsx "use client"; import { usePathname } from "next/navigatio ...

Choosing between creating a class with a shared instance or not

I'm curious if my class is shared across instances: for example, I have a route that looks like this: /student/:id When this route triggers the controller (simplified version): module.exports = RecalculateStudents; const recalculateActiveStudent ...

Challenges with focusing on TextArea inside a React MUI dialog

Having trouble implementing a multiline TextField within a dialog component. This issue has been causing me some difficulties for a while now. I'm not sure if it's related to Material-UI or possibly how my react page (dialog) is re-rendering. C ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

Caution: The `id` property did not match. Server: "fc-dom-171" Client: "fc-dom-2" while utilizing FullCalendar in a Next.js environment

Issue Background In my current project, I am utilizing FullCalendar v5.11.0, NextJS v12.0.7, React v17.0.2, and Typescript v4.3.5. To set up a basic calendar based on the FullCalendar documentation, I created a component called Calendar. Inside this comp ...

When trying to append in jQuery, the error "JQuery V[g].exec is not a

Attempting to create a script that adds a table to a div within the website using the following function: function generateTable(container, data) { var table = $("<table/>"); $.each(data, function (rowIndex, r) { var row = $("<tr/>"); ...

How come the styles in my CSS file aren't being applied to my images based on their class or ID?

When I apply a className or id to my img tag in my JavaScript (using React.js) and then add a style that references that id or class, the style does not get applied. However, when I do the same for a div, everything works perfectly fine. <--JavaScript- ...

Whenever I try to use Reactjs useState, an error always pops up

I am currently working with reactjs and utilizing the material-table to fetch data for an editable table. However, I have encountered an error similar to the image displayed. How can I resolve this issue? I have implemented useState for managing the edit ...

When the only source is available, the image undergoes a transformation

Is there a way to dynamically adjust the height of an image using JQuery or JavaScript, but only when the image source is not empty? Currently, I have an image element with a fixed height, and even when there is no source for it, Chrome still reserves sp ...

Is it possible to use a Backbone Model for an unconventional HTTP POST request that isn't

After going through the documentation at and , I tried to make an HTTP POST request to fetch some JSON data for my model. However, due to the services not being RESTful, I ended up using a POST request instead of a GET request. The code snippet I have co ...

Experience the visually stunning React Charts line chart featuring grouped labels such as months and weeks

Can you create a line chart in recharts with grouped points, such as displaying 6 months data series per day for about 180 days? Each point on the chart represents a day, but I want the X-axis labels to show the corresponding month like Jan, Feb, Mar, Apr, ...

Create a function in JavaScript that generates all possible unique permutations of a given string, with a special consideration

When given a string such as "this is a search with spaces", the goal is to generate all permutations of that string where the spaces are substituted with dashes. The desired output would look like: ["this-is-a-search-with-spaces"] ["this ...

Update the object continuously using the useState hook every second

I am constantly generating random numbers every 2 seconds and checking if these numbers exist as keys in my state object called data. If the number is found, I increment the value associated with that key; otherwise, I add it as a new field with a defaul ...

Dealing with an issue where Next.js router is not properly handling query parameters and returning them as undefined

Within my Next.js application, I have a page that functions as a search feature. The path for this page is structured like so: /search?q=search+slug. This specific page loads data on the client side and it's crucial to access the value of router.query ...

Tips for showcasing information from the tmdb api by leveraging the value or data obtained from a separate api

I am currently working on a project that involves displaying movie data using the tmdb api. I receive the response from my own api which only includes the id of the tmdb movie. Here is an example of the response: [ { "id": 0, "tit ...

What is the best way to show an HTML response from an API call on the DOM?

After making an API call, I receive the following HTML response and I am trying to display it on the DOM as actual HTML tags, rather than just showing text with HTML tags. API response: <strong>Hello</strong> Current DOM rendering: <str ...

Deploy Node.js on a Debian server hosted on Google Compute Engine

Currently, I am operating a Debian server on Google Compute Engine using a host called example.com. My goal is to run a node.js app within a specific directory on this server, for instance, example.com/mynodeapp. Fortunately, the necessary components such ...

Troubleshooting: Issue with WCF service not processing POST requests

I encountered an issue when attempting to call a WCF service using AJAX from another project. The error message displayed was: The server encountered an error processing the request. The exception message is 'The incoming message has an unexpected me ...