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

The dropdown menu in AngularJS is unable to retrieve the selected index

Presently, I have a dropdown menu: <select class="form-control" name="timeSlot" ng-model="user.dateTimeSlot" ng-change="dateTimeChanged(user.dateTimeSlot)" ng-blur="blur29=true" required style="float: none; margin: 0 auto;"> ...

Can you explain the purpose of prevState within the setState method of a functional component?

When returning the updated previous state within a setState method retrieved from the useState hook, it appears that the state remains unchanged. To demonstrate this behavior, consider running the following code snippet: function App(){ const [state, ...

Fetch several images simultaneously from a photo collection using JavaScript by generating a batch process

I need help with creating an image gallery that allows users to download multiple images by selecting them. The download should result in a zip file. I have checkboxes for selecting the images, but I'm struggling to figure out how to enable the downlo ...

Issue encountered when attempting to serve JSON response using Node.js, express, and MongoDB after the initial response

I have been experimenting with creating simple RESTful APIs using Node.js, Express, and MongoDB. For this purpose, I am utilizing the Node.js-MongoDB driver in conjunction with the Express framework. const MongoClient = require("mongodb").MongoClient cons ...

Is it possible to create an API directly within the URL of a React.js application, similar to how Next.js allows?

When using Next.js, I can access my application on localhost:3000, and also access my API from localhost:3000/api/hello. I'm curious if there is a way to achieve this same setup with React.js and another framework like Express.js? If Next.js is not ...

Replace the image source with a list of images

I am looking to create a dynamic image list using either an array or an HTML list. When I hover over an image, it should change one by one with a fade or slide effect, and revert back to the default images when I hover out. Question 1: What type of list s ...

How can I make an HTML button the default option within a form?

Currently, I am working on an asp.net page which contains a mix of asp.net buttons and HTML input[type=button] elements. These HTML buttons are specifically used to initiate AJAX calls. My dilemma arises when the user hits ENTER - instead of defaulting to ...

Implementing V-model within an iteration

I am encountering an issue while trying to utilize v-model within a v-for loop, resulting in an error message. Is there a solution to make this functionality work properly? <ul class=""> <li class="" v-model="category.data" v-for="category in ...

Activating a inaccessible element

Attempting to enable a disabled element upon clicking a P element, the following code snippet demonstrates storing a value from one textbox into another. The appended div contains a subsequent textbox which will be disabled. On mouseover of the div, option ...

Encountered an issue with getServerSideProps: Hydration error due to initial UI not matching server-rendered content

Utilizing an Urql client to execute a query on my graphql server currently. The query implementation is as follows: const username = () => { const { t: translation } = useTranslation(["common", "profile"]); const { ...

JavaScript form callbacks in Rails 3 are failing to trigger

My Rails 3 callbacks are not triggering for some unknown reason. Here's the form code I'm using: <%= form_tag('/create', :method => "post", :remote => true ,:id => "create") do %> <% end %> And this is the javascr ...

If the condition is met with the presence of X in the string, execute one action; otherwise, proceed with

Currently, my code successfully grabs the results: module.exports = async function grabResult(page) { const message = await page.$eval( 'div > div:nth-child(2)', (el) => el.innerText ); const username = await page.$eval( ...

Dynamic Searching in ASP.NET Core MVC Select Component

I need assistance with implementing a dynamic search feature on my Login page. Here's the scenario: When a user enters a username, let's say "Jh" for Jhon, I want to display a select list next to the login form that lists all the usernames from t ...

I'm encountering an issue with the MUI DateTimePicker where I'm getting a TypeError that says "value.isValid is not a function at Adapter

Having some trouble with the MUI DateTimePicker component from the @mui/x-date-pickers library when using Day.js as the date adapter. Every time I attempt to utilize the DateTimePicker with Day.js, I encounter the following error: value.isValid is not a ...

Using JQUERY to toggle classes conditionally

$('.showall').css("cursor","pointer").click(function() { $('.value-container').toggle(); $('.dim-header').toggleClass($('.dim-header').toggleClass() == 'dim-header' ? 'dim-header active' : & ...

Create a toggle effect using attribute selectors in CSS and JavaScript

I am looking to switch the "fill: #000;" from the CSS property "svg [id^='_']". Usually, I would use a method like this, but it seems that I can't do so because "svg [id^='_']" is not an element, correct? pub.toggleClass = functi ...

When applying animations to ngIf, the elements end up overlapping

I'm struggling to animate div elements when toggled using the Angular directive *ngIf. The issue I'm facing seems to be a common delay/timing problem in animations, but I haven't been able to find a solid solution. 1) When the current elem ...

The http url on an iPad in the src attribute of an HTML 5 video tag is malfunctioning

Having trouble loading a video on iPad using an http URL in the src attribute of an HTML5 video tag. Both static and dynamic approaches have been attempted, but it works fine on web browsers. Here is an example of the code: Static: <!DOCTYPE html ...

Retrieve data from an array of JSON objects within a JSON object using ReactJS

Trying to extract data from JSON like this: { "id": 371, "city": "London", "name": "London Station", "trains": [ { "id": 375, "number": "1023", "numberOfCarriages": "21" } ] } Interes ...

Step-by-step guide on importing SVG images in next.js with the file-loader

I've implemented the following loading configuration: config.module.rules.unshift({ test: /\.svg$/, use: { loader: 'file-loader', options: { esModule: false, name: '[name]-[hash].[ext]', outputPat ...