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

JavaScript allows for inserting one HTML tag into another by using the `appendChild()` method. This method

My goal is to insert a <div id="all_content"> element into the <sector id="all_field"> element using Javascript <section id="all_field"></section> <div id="all_content"> <h1>---&nbsp;&nbsp;Meeting Room Booki ...

I'm having trouble asynchronously adding a row to a table using the @angular/material:table schematic

Having trouble asynchronously adding rows using the @angular/material:table schematic. Despite calling this.table.renderRows(), the new rows are not displayed correctly. The "works" part is added to the table, reflecting in the paginator, but the asynchron ...

How can I revert a date format using date-fns?

Greetings from Thailand! I have a question regarding the reverse formatting using date-fns. Is there a way to create a function that will change "saturday-9-september-2564" back to "2022-09-24" using date-fns? Any insights or methods on achieving this wo ...

How can I create an efficient chat system using Ajax and settimeout without causing excessive virtual memory usage?

I'm in the process of creating a chat application using AJAX that fetches data every second with setTimeout. I have drafted a basic code where there is a number that increments each second by the number retrieved from the PHP page2. Upon testing it on ...

Submitting the form may cause disruptions for others

I currently have an email subscription form for my newsletter that is managed through PHP. This form appears in the footer of every page on my website. Check out a demonstration on JSFIDDLE While the form itself functions properly, I am encountering issu ...

Tips for persisting objects created in PHP while utilizing XMLHttpRequest

Currently, I am working on a web page with the index.php file structured as shown below: include('UserClass.php'); include('html/top.php'); $user = new User(); if (isset($_POST['user'], $_POST['pass'])) { $user-& ...

What is the method for transmitting a YAML file in the form of a base64 encoded string?

I am attempting to transmit a yaml file as a base64 string in order for this code to function: const response = await octokit.request('GET /repos/{owner}/{repo}/git/blobs/{file_sha}', { owner: 'DevEx', repo: 'hpdev-content&apos ...

Guide: How to transfer the output from MongoDB in Node.js to AngularJS?

Currently, I am using Node.js to query my data from a MongoDB database. However, I am facing an issue where the data is not being sent out as expected when running this particular function. var findIco = function(db, callback) { var cursor = db.collec ...

Is there a way I can incorporate v-for with a computed variable?

I am trying to display navigation items based on my authority and other conditions. Below is the code I am using: <template v-for="(subItem, index2) in item.children"> <v-list-item sub-group link :to="subItem.link" exact ...

AngularJS Splice Function Used to Remove Selected Items from List

I previously inquired about a method to remove items from the Grid and received a solution involving the Filter method. However, I am specifically looking for a way to remove items using the Splice Function instead. You can find my original question here: ...

Several mistakes occurred involving auth0, react, apollo, babel, and webpack

I seem to be facing some challenges while trying to integrate auth0 into my project. Every time I fix one issue, another one pops up and it's always the same trio of errors: -require is not a function -window is not defined -missing class properties ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

Frequently, cypress encounters difficulty accessing the /auth page and struggles to locate the necessary id or class

When trying to navigate to the /auth path and log in with Cypress, I am using the following code: Cypress.Commands.add('login', (email, password) => { cy.get('.auth').find('.login').should(($login) => { expect($log ...

When making recursive AJAX calls, the script that is included between each recursion is not being executed

My recursive Ajax call is functioning correctly (the PHP script is doing its job, recursion is working, everything is fine) EXCEPT that in between the ajax calls, I am trying to update an input text value to show the progress, but it only updates once the ...

The requested function is nowhere to be found within the confines of my Controller module

While working on a personal project, I encountered an issue where a function from another class in a separate Java file is not being found, even though it is defined in the respective class. EventView.js: displayEvent(event){ this.EventTitle = event. ...

Google Maps in Angular is not showing up

My Angular Google Maps implementation seems to be working, but unfortunately, the map is not showing on my website. I have confirmed that my JS is loading the maps and I can retrieve the map properties. Interestingly, when I check the Chrome AngularJS Debu ...

Cease hover effect animation

Whenever I hover over the main span, the animation works perfectly. However, once I move the cursor away from it, the animation continues to run. How can I make it stop, and why does it persist? $('#menu span:first').hover(function (){ functi ...

Issue with passing parameter values in MVC Html.ActionLink

Currently, I am experimenting with MVC for a demonstration and have managed to put together some components. However, I am encountering difficulties with an Html.ActionLink. The goal is to display a series of dropdown lists to the user that must be selecte ...

Use the knockout textInput plugin in combination with the maskedinput plugin

Is there a simple way to use data-bind="textInput: aProperty" and apply an input mask or automatic formatting while the user is typing? Although using the masked input plugin somewhat works, it results in losing the real-time updates that Knockout's ...

Is there a way to update and save both dependencies and devDependencies with a single command in Npm?

Is there a way to update multiple npm dependencies and save them to their respective locations in the package.json file? This is what my package.json looks like: { "dependencies": { "gulp": "^3.0.0" }, "devDependencies": { "gulp-eslint" ...