Transferring information between components and pages within Next.js involves the passing of data

I currently have an index page set up like this:

getServerSideProps(){
//Making two API calls here
api1()
api2()
return{
props:{data:gotDataApi1, data2:gotDataApi2}
}
}

The data retrieved from these APIs is then passed to a component within the index page like so:

<component1 gotData1={gotDataApi1} gotData2={gotDataApi2}/>

Everything seems to be working fine with this setup. However, I now have a component where user interactions provide parameters for calling the next required API. Within this component, I've added a Link that passes user values like this:

<Link 
  href={`indexpage?paths=${parameter1}/${parameter2}/${parameter3}`}>
</Link>

Upon receiving these parameters in getServerSideProps(context), I use them to call another API. This call sometimes results in an error related to 'split undefined' as shown below:

const {params, req, res, query} = context;
var str = query.paths;
console.log(str); // Output: 2022/1/1001
const splitStrings = await str.split("/ ");

The sliced values are then used for another API call like this:

This is the api3() call: const response4 = await fetch(

http://localhost:3000/api/${splitStrings[0]}/${splitStrings[1]}/${splitStrings[2]}
); const data4 = await response4.json();

I'm looking to replace the existing structure with something like this:

<component1 gotData1={gotDataApi1} gotData3={gotDataApi3}/>

I've created a [...slug].js page which requires rendering the entire component similarly to my index page. The index page contains a side menu, and that code also needs to be included here:

<Side years={data2} chapters={data3} />
<component1 gotData1={gotDataApi1} gotData3={gotDataApi3}/>

The [...]slug].js page looks very similar to my index page. If anyone has suggestions on how to tackle this challenge, whether it involves using useEffect or following any standard practices, please let me know. Your assistance would be greatly appreciated.

Answer №1

Thanks to a friend, I was able to get the answer.

const sampleArray =[];
if(query.paths){
    var str = query.paths;
    const splitStrings = str.split("/");
    const response4 = await fetch(`http://localhost:3000/api/${splitStrings[0]}/${splitStrings[1]}/${splitStrings[2]}`);
    sampleArray = await response4.json();
}                                                                                                                                           
const finalData = sampleArray.length > 0 ? sampleArray : data1; 

I successfully passed the data to the index page without creating a [...slug] 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

What is the best way to arrange the keys of a JavaScript object in a customized

I am struggling to find a way to custom sort a JavaScript object properly. For example, I have the following object: var test = { 'yellow': [], 'green': [], 'red': [], 'blue': [] } And an array with values ...

the slider HTML control is missing a value

Exploring the Range Input Type in HTML When adjusting the value on a slider (Range input type), that value is displayed in a textbox. However, making the same adjustment in the textbox does not update the slider's value. Below is the code snippet: & ...

What is the process for setting up a resthook trigger in Zapier?

I'm currently integrating Zapier into my Angular application, but I'm struggling with setting up a REST hook trigger in Zapier and using that URL within my app. I need to be able to call the REST hook URL every time a new customer is created and ...

Tips for notifying a user prior to navigating back using the browser's back arrow in NextJS

Within my NextJS application, there is a page that displays a modal based on the presence of a query parameter. The modal opens when the query parameter is set and closes when it is not present. Since the modal contains a form, I need to notify the user i ...

What could be causing the model to not bind correctly in nodejs?

In the process of developing a web app with nodejs, angular, and mongo, I have encountered a strange issue. The model is not binding properly from the JSON object. Here is my Schema: var mongoose = require('mongoose'); var productSchema = new ...

Ajax fails to function within a loop

I'm looking to implement Ajax in a loop to retrieve data sequentially. This is what I have in my JavaScript function: var resultType = $("input[name='resultType']:checked").val(); var finalResult = ""; var loadingMessage = "<img src=&ap ...

A guide on displaying a JSON object using the ng-repeat directive

Looking to create a dynamic treeview menu with angularJS? Wondering how to achieve the desired results using a controller ($scope.results) and JSON data? Check out the code snippet below for an example of how to structure your treeview: <ul> < ...

When working with Angular 12, the target environment lacks support for dynamic import() syntax. Therefore, utilizing external type 'module' within a script is not feasible

My current issue involves using dynamic import code to bring in a js library during runtime: export class AuthService { constructor() { import('https://apis.google.com/js/platform.js').then(result => { console.log(resul ...

Node.js readline: SyntaxError: Unexpected token =>

Currently, I am diving into node.js and have found myself in need of utilizing the readline module for a new project. Below is the code snippet that I extracted directly from the official readline module example. const readline = require('readline&ap ...

What is the best way to add data to my collection using the main.js file on the server side in a Meteor application

I am a beginner with Meteor and trying to customize the tutorial codes. I have a code that listens for packets on my server-side main.js. Now, I need to store the data printed on the console into my database collection. import { Meteor } from 'meteor/ ...

Transmit parameters via onclick event on FullCalendar

I have been utilizing the full calendar feature and it's been functioning properly. However, I am encountering an issue with sending parameters via onclick event. Below is the JavaScript code that I currently have: <script> $(document).ready(fu ...

Combining Arrays in AngularJS with an owl-carousel Setting

My goal is to implement an endless scrolling carousel in AngularJS using owl-carousel. The idea is to load new items every time the carousel is fully scrolled and seamlessly merge queried elements with the existing list. However, I've encountered a pr ...

Seeking the value of a tab text using Selenium's web driver

Greetings! Currently, I am exploring the integration of selenium webdriver with mocha and node js in order to automate testing for a Single Page Application (SPA). My objective is simple - to locate a specific tab and perform a click action on it. The HTML ...

Success function in AJAX triggered when no JSON data is returned

Despite its simplicity, I'm having trouble getting this right. I'm utilizing jQuery/AJAX to fetch data (in the form of JSON) from my database. Upon successful retrieval, I have a function to display the data. While this works as expected, I now a ...

Looking for assistance with retrieving all files from a directory based on their file extensions in JavaScript

Looking for a way to gather all the '.txt' files from a folder that also contains a 'backup' folder, and moving them into the 'backup' folder using Node.js. If you have any suggestions, please share. Thanks! Best regards, M ...

Why use getElementById(id) to obtain an element in JavaScript when it already exists in the JS?

Recently, I have observed that a reference to an HTML element with an id can be easily accessed in JavaScript by using a variable named after that id (jsbin). What is the reason for this behavior? Why do we need to use getElementById(id) when we could sim ...

Necessary within a JavaScript Class

As a newcomer to using classes in JavaScript, I've been exploring the best practices and wondering about how 'requires' work when used within a class. For example, let's say I want to craft an IoT Connection class for connecting to the ...

What is the process of statically importing an image using next/image?

When attempting to statically import an image for use with next/image, an error keeps appearing: ./public/IMG_2117.png Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to handle this file type, currently no lo ...

Unable to parse the request body in a nextjs 13.4 app router when using APIs endpoint POST and json()

async function handlePostRequest(req: Request) { try { const requestBody = await req.json() console.log(requestBody); return new Response("ok") } catch (error) { console.log(error); } } When attempting to send a payload usin ...

The "variable" used in the React app is not defined, resulting in a no

Following the tutorial of Mosh Hamedani, I attempted to create a react-app. You can watch the tutorial here. I followed his instructions exactly as mentioned. I encountered an issue when trying to pass an argument named product to a function called on on ...