What could be causing the failure of the JSON parse for dynamic link parameters?

I am currently attempting to pass parameters to a dynamic page within an Amplify/NextJS application.

This is still a work in progress. My objective is to utilize the passed parameters to generate a basic page based on 4 parameters included in the URL invocation.

The issue I am encountering is that when I make modifications beyond just a few statements in the dynamic page file, the parameters cease to be passed - or more likely, they are somehow getting corrupted.

The code for the dynamic page file ([id].js) is quite straightforward:

import {useRouter} from 'next/router'

export default function Detail() {
    const router = useRouter()
    console.log('router', router)
    const {id, params} = router.query
    console.log('id', id)
    console.log('params', params)
    // const parsed = JSON.parse(params)

}

Below is the code that triggers the page (note the JSON.stringify() in the onClick() function):

export function GetDanzanRyuCollection(narration, items, path) {

    return (
        <>
            <View>
                <Text>
                    {narration}
                </Text>
                <Collection
                    type="list"
                    items={items}>
                    {(item, index) => (
                        <View
                            key={index}
                            onClick={() => {
                                let parms = JSON.stringify(item)
                                window.location.href = `./${path}/${item.Number}?params=${parms}`
                            }}>
                            <Card
                                width={"40rem"}
                                variation={"elevated"}
                                key={index}
                                padding="1rem"
                                textAlign={"left"}
                                backgroundColor={"blue.20"}
                                fontSize={"1.5rem"}>
                                <Flex
                                    direction="row"
                                    justifyContent="flex-start"
                                    alignItems="flex-start"
                                    alignContent="flex-start"
                                    gap="1rem">
                                    <Text
                                        width="2.25rem">
                                        {item.Number}
                                    </Text>
                                    <Text
                                        isTruncated="true"
                                        height="3.0rem"
                                        width="15.25rem">
                                        {item.Name}
                                    </Text>
                                    <Text
                                        isTruncated="true"
                                        height="3.0rem"
                                        width="19.25rem">
                                        {item.Description}
                                    </Text>
                                    <Rating
                                        maxValue={1}
                                        value={item.Variations.length}
                                        icon={<ImVideoCamera/>}/>
                                </Flex>
                            </Card>
                        </View>
                    )}
                </Collection>
            </View>
        </>
    )
}

When using the unaltered code above, I see the expected output in my browser log. In other words, the parameters are successfully passed:

https://i.stack.imgur.com/0NA5k.png

However, if I uncomment the

const parsed = JSON.parse(params)
statement (above), the following output appears in the log (noting that both id and params now display as undefined):

https://i.stack.imgur.com/c4xgI.png

So, what mistake am I making? Additionally, why are there multiple calls to the [id].js file function for a single click?

Appreciate your assistance,

Answer №1

It is important to encode any special characters in the JSON before using it in URLs:

const encodedData = encodeURIComponent(JSON.stringify(data))

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

Combining an Image with a CanvasJS Graph and Generating a Downloadable Image of the Composite

I am attempting to combine an image (a background image for my graph) with my canvasJS chart. Once these elements have been merged on a canvas, I aim to obtain a DataURL of this canvas, enabling me to download an image of it (depicting the graph along wit ...

Importing Laravel select2 library is necessary for enhancing user experience and improving

I've been attempting to incorporate select2 into my project without success. Every time I try these two methods, I always receive an error saying $('#state').select2 is not a function. However, when I include select2 in a standard <scrip ...

AngularJS does not allow access to the variable value outside of the resource service's scope,

I have developed an AngularJS factory service to handle REST calls. The service is functioning correctly, but I am facing a challenge where I need to set values into $scope.variable and access them outside of the resource service. However, when attempting ...

Step-by-step guide on positioning an image to show at the bottom of a div

I am trying to create a div that covers 100% of the screen height, with a table at the top and white space below it for an image. However, when I add the image, it ends up directly under the table instead of at the bottom of the DIV. I have searched on G ...

Unable to establish a connection with the default port on Mongo DB while utilizing Node.js

I am new to using Node.js and I'm trying to establish a connection with MongoDB in my Node.js application, but I'm encountering issues. Here is the code snippet: var mongo = require("mongodb"); var host="127.0.0.1"; var port=mongo.Connection.DE ...

Having difficulty in converting JSON objects into key/value pairs in Angular 7

I have a task to convert my JSON data from its current format as shown below: cacheMapDataDto = [{ "cacheName": "cache_nchl_individual_type", "count": 2, "mapObj": { "NCHL_BI_BATCH_VERIFICATION": false, "NCHL_STL_BATCH_VERIFICATIO ...

The entire space should be filled with the background

My goal is to achieve the following while addressing some current issues: The background is currently limited to affecting only the container. I want it to span the entire area. There needs to be space between the cards and padding inside them. https://i ...

Error in Typescript: The type 'Element' does not have a property named 'contains'

Hey there, I'm currently listening for a focus event on an HTML dialog and attempting to validate if the currently focused element is part of my "dialog" class. Check out the code snippet below: $(document).ready(() => { document.addEventListe ...

Prevent typing in text box when drawer is activated by pressing a button

update 1 : After removing unnecessary files, I need assistance with https://codesandbox.io/s/0pk0z5prqn I am attempting to disable a textbox. When clicking the advanced sports search button, a drawer opens where I want to display a textbox. The toggleDra ...

Having trouble with JQuery click function not executing on initial click?

As I scoured through various resources looking for solutions to issues similar to mine, I stumbled upon numerous helpful insights. However, after going through approximately 15 of them, I hit a roadblock in finding someone who has encountered the exact sam ...

Can the JavaScript code be altered within the client's browser?

So, I'm using JQuery Validator on my webform to validate form data. However, I haven't added any validation on the server side. I'm curious if it's possible for a user to modify the code and bypass my validations in their browser. If th ...

Retrieving live information from an API in order to populate a specific route

Utilizing the contents of two crucial files to extract data from separate APIs, here is my simplified example: poloniex.js const Poloniex = require('poloniex-api-node') const poloniex = new Poloniex() async function obtainExchangeData() { po ...

Can the data retrieved from a jsonp call that may be considered "bad" be utilized effectively?

When making a JSONP call to another domain, I am receiving data that is in JSON format but not wrapped in a function. This causes a parse error to occur. However, the data is still retrievable and visible. Despite the error, is it possible to utilize the ...

Vanilla JavaScript: Enabling Video Autoplay within a Modal

Can anyone provide a solution in vanilla JavaScript to make a video autoplay within a popup modal? Is this even achievable? I have already included the autoplay element in the iframe (I believe it is standard in the embedded link from YouTube), but I stil ...

The onClick() function in JavaScript is encountering issues on the Firefox OS mobile application

I've been working on an app for Firefox OS mobile devices where I'm trying to trigger a Javascript function onClick() from a div attribute. It's functioning properly in regular browsers, but when I test it in the simulator, the onClick funct ...

Having trouble grouping data on website due to duplicate names

Currently in the process of scraping data from various websites and looping through it. Specifically focusing on scraping the head section. This is an example illustrating the structure of the data: const head = { rel_data: [ { rel: &quo ...

What is the best way to center align an element while having another element situated directly below it?

I want to create a grid of "clock" elements, with five clocks in each row. Below each clock, I'd like to display the DAY and DATE centered with the clock (day on top line, date below). Since I'm new to html/css, I appreciate your patience. Here&a ...

Error encountered: Vue.js encountered an unexpected token, which is 'export'

Having an issue with Google location autocomplete, specifically this error: SyntaxError Unexpected token 'export' Here is the link to the functional code: https://codesandbox.io/s/nifty-bardeen-5eock ...

Display or conceal elements using the unique identifier selected from a dropdown menu in JavaScript

I have been searching the internet for a solution to my issue but nothing seems to be working. Here is the problem: Unfortunately, I cannot modify the TR TD structure and am unable to use DIVs. I am trying to dynamically display certain TD elements based ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...