Discover how to generate nested dynamic routes in NextJS by linking to MongoDB data using the getStaticProps and getStaticPaths functions

Currently, I am facing a challenge with implementing dynamic paths in NextJS and I'm struggling to find a solution. Let me provide some context for better understanding.

I am working on developing an ecommerce application using NextJS, and the folder structure looks like this: Home / [ShopID] / Categories / [CategoryName] / [ProductName]

The MongoDB setup is structured as follows:

{ShopID: <given mongodb id>,
ShopName: <Shop Name>
ShopCategories: {
Category1: {
CategoryDetails: <Pairs for category name, id, etc>,
CategoryProducts: {
Product1:{
ProductDetails: <Pairs for product name, id, etc>,}
}}}}

My aim is to create a version of the website where shop owners can easily add categories, products, and manage their store smoothly.

The desired functionality includes:

"//" = Clicking a button on the home page to navigate to /[ShopID] from the database (initially set up as a button without authentication), leading to a dashboard page. "/[ShopID]" = Dashboard with buttons pointing to various sections such as "Categories and Products". Clicking it should redirect to "/[ShopId]/categories". "/[ShopID]/categories" = Display React Component Buttons for each category containing picture, name, etc. Clicking a category leads to "/[ShopID]/categories/[CategoryName]". "/[ShopID]/categories/[CategoryName]" = Contains React Component Buttons for each Product that direct to "/[ShopID]/categories/[CategoryName]/[ProductName]".

Here are snippets of the relevant current code:

"/"
<Link href=""><div><h1>To home</h1></div></Link>

Initially, I hardcoded the /[ShopID] Link paths as "/id" and need guidance on setting up the Link href="" properly.

"/[ShopID]"
import HomepageButton from "../../components/homepage/Homepage-Button"

<main className="maincontainer">
<HomepageButton item="home-category" label="Categories & Products"></HomepageButton>
...

I have encountered challenges with passing data down through components and structuring getStaticProps and Paths. How can I resolve these issues?

...

Any assistance or guidance on these matters would be highly appreciated. Feel free to ask if you have any questions.

Answer №1

After realizing I could consult chat GPT, it ended up providing me with the solution I was looking for following some adjustments.

function ShopID({ item }){
const router = useRouter()
const {shopid} = router.query

const { shopCategories } = item.shopData

console.log(shopCategories)


return <Fragment>
    <h1>The shop place</h1>
    <h1>{shopid}</h1>
    <h2>{item.name}</h2>
</Fragment>
}

export default ShopID


export async function getStaticProps({ params }) {
// Establish connection to MongoDB database
const client = await MongoClient.connect(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const db = client.db();

// Retrieve the item from MongoDB collection based on ID parameter
const id = new ObjectId(params.shopid);
const item = await db.collection('shops').findOne({ _id: id });

item._id = item._id.toString();

// Close MongoDB client
client.close();

// Return item as props
// return { props: { item } }

return {
    props: { item },
    revalidate: 1 // seconds before page regeneration
  };
  }


export async function getStaticPaths() {
// Establish connection to MongoDB database
const client = await MongoClient.connect(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const db = client.db();

// Fetch all item IDs from MongoDB collection
const items = await db.collection('shops').find({}, { projection: { _id: 1 } }).toArray();

// Generate paths list based on item IDs
const paths = items.map((item) => ({
  params: { shopid: item._id.toString() },
}));

// Close MongoDB client
client.close();

// Return list of paths
return { paths, fallback: false };
}

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

Selenium unable to interact with Javascript pop-up box

I am currently working on automating a feature for our web application, specifically a form of @mentioning similar to Facebook. On the front end, when a user types @ into a text input, the API is called to retrieve the list of users and display them in a b ...

Why is the console log not working on a library that has been imported into a different React component?

Within my 'some-library' project, I added a console.log("message from some library") statement in the 'some-component.js' file. However, when I import 'some-component' from 'some-library' after running uglifyjs with ...

The MUIv5 and tss-react SSR problem persists: Difficulty in consistently managing style definitions due to ArrowFunctionExpression in CSS prop

Currently in the process of upgrading my mui to v5 and encountering challenges with the makeStyes "interpolation" pattern as outlined below: const useStyles = makeStyles((theme) => ({ root: { backgroundColor: (props) => { let bgColor = " ...

Removing a parameter from a variable in jQuery and JavaScript

I have coded something and assigned it to a variable. I now want to replace that value with another one. Just so you know, I do most of my coding in perl. Specifically, I am looking to remove the menu_mode value. Any advice on this would be greatly appre ...

What could be causing my state not to change in Nextjs even though I followed the quick start guide for Easy Peasy?

I recently encountered an issue while trying to implement easy peasy for global state management in my nextjs app. The problem I faced was that the state would only update when I changed pages, which seemed odd. To better understand what was going on, I de ...

Returning draggable elements to their original placement

I'm looking to create a custom function that resets my draggable elements to their original positions when invoked. This is not related to the built-in revert functionality. $('.drag').draggable({ stack: ".drag", snap: ".dro ...

What is the best way to correctly render several React components using a single index.js file?

I am facing an issue with rendering two React component classes. One class creates a counter and works fine, while the other class generates a simple string wrapped in HTML tags but does not render. I have tried various tutorials to troubleshoot this probl ...

Issues with the Diagonal HTML Map functionality

I'm seeking assistance to implement a unique Google Maps Map on my webpage. I have a particular vision in mind - a diagonal map (as pictured below). My initial approach was to create a div, skew it with CSS, place the map inside, and then skew the ma ...

Customize the color of badges in React using Material-UI components

Is there a way to customize the colors of badges in React MUI v5, specifically overriding the default primary and secondary colors? I attempted to use the createTheme method as shown below: const CustomTheme = createTheme({ palette: { type: 'da ...

I am encountering an issue trying to create a Docker image featuring TypeScript

I am facing an issue while trying to build a docker image using the docker build . command in my next.js app An error is being encountered Error: buildx failed with: error: failed to solve: process "/bin/sh -c yarn run build" did not complete su ...

What is the most effective way to import a substantial static array in React for utilization in a select field?

The scenario is quite straightforward. I currently have a single array containing over 2500 strings of company names, saved locally in the project as a JSON file within a subdirectory under src. To access this data in my component, I am importing the JSON ...

Utilizing JavaScript text variables as hidden inputs

My JavaScript code is responsible for populating a modal from various sections of a website. Essentially, when the modal expansion button is clicked, it collects all data associated with that particular button press. While this functionality works flawles ...

Having trouble retrieving custom headers in a react response

I currently have a frontend built with react, flux, and node, while the backend is developed using Java. I am utilizing superagent to send requests from the react action to the backend, which is functioning correctly. Moreover, I have set up custom headers ...

Error: Invalid connection string for ELF Lambda detected

Having an issue with a lambda function that connects to a remote MongoDB on an EC2 instance using TypeScript. While I can connect to the database locally, there is an ELF error when running in lambda. It seems to be related to mismatched binaries of npm pa ...

In TypeScript, the catch block does not get triggered

I created a custom pipe in Angular that is supposed to format passed parameters to date format. The pipe contains a try-catch block to handle any errors, but surprisingly the catch block never seems to be executed even when an invalid date is passed. impo ...

Error: A SyntaxError was encountered due to a missing closing parenthesis after an argument list while writing JavaScript within PHP code

I'm facing an issue writing JavaScript within PHP code. Here's my script : echo ' <script>'; echo ' $(function(){'; echo ' x = parseInt($("#counter2").val());'; echo ' $("#add_row2").click(function(){&apo ...

Encountering the error message "BarChart in react.js is not iterable"

I encountered an issue with the BarChart component: An error message saying "undefined is not iterable!" appeared. The API response I received looks like this: { "saleCharts": [ { "priceSum": 0, "categoryName&q ...

Exploring ways to run tests on a server REST API using testem

When using Testem, I have a config option called serve_files that handles serving the client-side code for me. However, I also need to run my server because it includes a REST API that the client side relies on. Is there a way to configure Testem to launc ...

Retrieve the current height of the iFrame and then set that height to the parent div

Within a div, I have an iFrame that needs to have an absolute position for some reason. The issue is that when the iFrame's position is set to absolute, its content overlaps with the content below it. Is there a way to automatically adjust the height ...

What is the best way to deliver hefty files to users? Utilize the node-telegram-bot-api

bot.sendDocument(id, 'test.zip'); I am facing an issue while trying to send a 1.5GB file using the code above. Instead of being delivered to the user, I receive the following error message: (Unhandled rejection Error: ETELEGRAM: 413 Request En ...