Retrieving JSON information using dynamic routes in Next.js

I am working with a json file that contains content for various pages categorized under "service". In my nextJS project, I utilize dynamic routes with a file named "[serviceId].tsx" for routing. This setup is functioning correctly. However, I am facing an issue where I need to access information from the json file using the [serviceId] provided in the route.

Here is the code snippet from my [serviceId].tsx file:


    const json = jsonFile.services  
    const router = useRouter()
    const serviceId = router.query.serviceId
  

  return (
      <div> 
        <ArticleWithPicture title={content.title} description={content.description}/>
    </div>
  )
}

My json file has a structure similar to this (edited for clarity in this example):


        {
            "serviceId":
                [
                    {
                        "service1": {
                        "id": "xx",
                        "title": "xxx",
                        "description": "xx",
                        "featuredCompany":
                            [
                                { "id": "1", 
                                   "name": "xxx",
                                   "companyPageURL": "/",
                                   "imagePath": "xxx",
                                   "description": "xxx",
                                   "additionalServices": {
                                   "service1": "xxx",
                                   "service2": "xxx"
                                },
                                   "instagramURL":"/",
                                   "twitterURL": "/" 
                                }
                            ]
                        }           
                    },
                    {
                        "service2": {
                        "id": "xxx",
                        "title": "xxx",
                        "description": "xxx",
                        "featuredCompany":
                            [
                                { "id": "1", 
                                   "name": "xxx",
                                   "companyPageURL": "/",
                                   "imagePath": "xxx",
                                   "description": "xxx",
                                   "additionalServices": {
                                   "service1": "xxx",
                                   "service2": "xx"
                                },
                                   "instagramURL":"/",
                                   "twitterURL": "/" 
                                }
                            ]
                        }           
                    }                   
                ]
        }


Each Service in the json file corresponds to individual pages. My objective is to dynamically set the title of the "ArticleWithPicture" component based on the title in the json file that matches the serviceId obtained from "router.query.serviceId". However, the code snippet below results in an error:

<ArticleWithPicture title={json.{serviceId}.title}/>

This issue is due to nesting curly braces. Is there a better way to approach this?

Directly accessing the title like this also does not work:

const title = json.serviceId.title

My actual goal is to query the json file based on the serviceId provided by "router.query.serviceId" like this:

 const title = json.{serviceId}.title

It seems like there could be a problem either with my json file structure or my method of accessing it. Any guidance on this matter would be greatly appreciated.

Thank you!

Answer №1

It seems like the JSON you provided encompasses your entire jsonFile. If the JSON you provided only represents jsonFile.services, then you should substitute any instances of jsonFile with jsonFile.services and adjust the type accordingly.

The structure of the JSON may not be optimized for your particular scenario due to excessive nesting.

Considering your current JSON

If you are unable to alter the JSON format, you will need to locate the service within the serviceId array:

function getService(json, serviceId) {
  return json.serviceId
    .find((serviceWrapper) => serviceWrapper[serviceId] !== undefined)
    ?.service;
}

Here is a fully typed example:

type Service = {
  id: string
  title: string
  description: string
  // ...
};

// This is optional, provided for clarity
type JsonFile = {
  serviceId: {
    [serviceId: string]: Service
  }[]
};

function getService(json: JsonFile, serviceId: string): Service | undefined {
  return json.serviceId
    .find((serviceWrapper) => serviceWrapper[serviceId] !== undefined)
    ?.service;
}

// declare const jsonFile: JsonFile;

export default function ServicePage() {
  const router = useRouter();
  const serviceId = router.query.serviceId as string;

  const content = getService(jsonFile, serviceId);

  if (!content) return (
    <div>
      {'Article doesn\'t exist.'}
    </div>
  );

  return (
    <div>
      <ArticleWithPicture title={content.title} description={content.description} />
    </div>
  );
}

With improved JSON

Here is an example of a JSON structure that requires less unwrapping:

{
  "service1": {
    "id": "xx",
    "title": "xxx",
    // ...
  },
  "service2": {
    "id": "xxx",
    "title": "xxx",
    // ...
  }
}
type JsonFile = {
  [serviceId: string]: Service
}

With this structure, you can simply access the service using jsonFile[serviceId] or jsonFile.services[serviceId].

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

Retrieve data from JSON using AJAX

I am working with an API that provides JSON data in the following format: [{ "Code": "001", "Name": "xyz", "Members": [{ "FullName": "User1" }] }, { "Code": "002", "Name": "asd", "Members": [{ "FullName": "User2 ...

Having trouble retrieving XSRF-TOKEN from cookie in Next.js (React.js)?

When working with Next.js and Laravel 8 backend, I encountered an issue where I couldn't set the XSRF-TOKEN generated by Laravel on my fetch request for login. Despite being able to see the token in the inspect element > application tab > cookie ...

Establishing the value of "document.cookie"

Encountering issues while trying to set a cookie using different methods: Method 1: document.cookie = name + "=" + value + "; expires=" + date.toUTCString() + "; path=/"; This method only sets the value up to "name=value" wh ...

Position the circles in a way that they align along the circumference of a larger

I need help arranging a group of circles around another circle without any of them overlapping. I have all the radius measurements for each circle, as well as the coordinates for the target circle. The target circle will always be large enough to contain ...

Which <object> should I use to link my elasticsearch database with the INCEpTION NER annotation tool?

Having set up a local environment for text annotation, I am interested in using the INCEpTION application developed at: https://github.com/inception-project/inception/blob/main/CONTRIBUTORS.txt While attempting to connect to my repository, I can successfu ...

The error message "Property 'list' is not found on type 'void' React - Material UI" indicates that the 'list' property is not recognized

Currently, I am facing an issue while working with Material UI and React Typescript. The error message I receive is "Property 'list' does not exist on type 'void'" when attempting to use makeStyles and createStyles to remove padding. It ...

Efficiently rendering web pages with Next.js

In my market application, I have a page that displays a list of products. Which rendering type would be the optimal choice for this scenario? Will Static Generation update the list when the page is refreshed? ...

attempting to employ a custom class for storing a JSON reply

I am currently working on creating a Java class that will store a JSON response structured like this: { "Global Quote": { "01. symbol": "IBM", "02. open": "160.0000", "03. h ...

The state update is paused by one state

Feeling a bit lost here, could be a beginner's mistake. Attempting to replicate the game of chess. Encountering a delay issue in my code.. basically, when I click on a square to display the possible moves for a piece, they only show up correctly aft ...

"GraphQL DefinitelyTyped: The go-to resource for TypeScript typings

I have been working on obtaining type definitions for graphql in my project. After installing both graphql and @types/graphql, I am using import * as graphql from "graphql" in my file. Despite this, I am encountering difficulties accessing certain types ...

Dynamic user input using an enumeration

I am looking to develop a flexible input component (in React) that can dynamically generate different types of inputs based on the enum type provided along with relevant inputProps. The idea is to switch between different input components based on the type ...

How can I simulate or manipulate the element's scrollHeight and clientHeight in testing scenarios?

In my JavaScript code, I have a function that checks if an HTML paragraph element, 'el', is a certain size by comparing its scrollHeight and clientHeight properties: function isOverflow(element: string): boolean { const el = document.getEleme ...

Utilizing Next.js to Manage Back Button Functionality

While developing the application I'm currently working on, I navigate through a series of pages. After reaching the final page and attempting to click the browser back button, I am wondering if there is a method to redirect to a different URL instead ...

Eliminating empty elements in json documents within a MongoDB database

Working with php and MongoDB, the library I am using automatically generates code for mongodb calls, acting as an ODM layer. However, when dealing with embedded documents in the parent document, the library utilizes the $unset function. According to the D ...

Leveraging C# and iOS to retrieve a JSON address via an API

As I work on developing a new Air Quality API-based app, I am reminded of when I attempted to create a weather app using JSON. Here was the initial code I had in place: var webClient = new WebClient(); ... var text = e.Result; // storing downloaded text ...

Best location to define numerous dialog components

Currently, I have 8 custom Modals that are called in various places within my app. These modals are currently located inside the app.component.html as shown below: <agc class="app-content" [rows]="'auto 1fr'" [height]=" ...

A guide to consuming JSON String arrays in Spring Boot

I'm facing issues with properly reading an input JSON file in my webservice. I'm trying to convert some input parameters from a simple String to an array of Strings The structure of my input JSON is as follows: { "inputParams" : { "speckle ...

JavaScript and TypeScript: Best practice for maintaining an Error's origin

Coming from a Java developer background, I am relatively new to JavaScript/TypeScript. Is there a standard approach for handling and preserving the cause of an Error in JavaScript/TypeScript? I aim to obtain a comprehensive stack trace when wrapping an E ...

Error encountered: React Typescript does not support the "any" type in a template literal expression

I have been encountering an issue with my slider component in React Typescript. The error message I keep getting is related to the "Invalid type 'any' of template literal expression" specifically at the const fillWidth variable. I am struggling t ...

The type 'function that takes in a CustomEvent and returns void' cannot be assigned to a parameter of type 'EventListenerOrEventListenerObject'

When I upgraded from TypeScript version 2.5.3 to 2.6.1, my custom event setup started giving me an error. window.addEventListener('OnRewards', (e: CustomEvent) => { // my code here }) [ts] Argument of type '(e: CustomEvent) => ...