Error: JSON input ended unexpectedly, and data retrieval is not possible

Encountering the following error message: SyntaxError: Unexpected end of JSON input

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

Modifying the code causes the page to endlessly load without stopping

Utilizing Next.js for development

The API directory being used is api/CreateComment

Code snippet for creating a comment:

export default async function CreateComment(req, res){

const { name, comment, _id } = JSON.parse(req.body)
console.log( name, comment, _id )

await client.config({
    token: process.env.SANITY_AUTH_TOKEN
}).create({
    _type: "comment",
    name,
    comment,
    blog:{
        _type: "reference",
        _ref: _id
    },
})
return res.status(200)

}

Despite the stated error, comments are successfully fetched and stored in the backend. The issue lies in the inability to retrieve them for display.

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

When running a console.log, the above image showcases the object being returned

However, attempting to fetch them from the frontend using the command below renders no results:

{JSON.stringify(comment)}

The output displayed in my slug.js file after executing the above command is not as expected

https://i.stack.imgur.com/4PPoI.png

Using comment.name or comment[0].name results in retrieving an undefined value

Responding to comments:

Code for the form section:

function Form({ _id }) {
const {
    register,
    handleSubmit,
    formState: { errors },
} = useForm();
const onSubmit = (data) => {
    
    fetch('/api/CreateComment', {
        method: "POST",
        body: JSON.stringify({ ...data, _id })
    })
}
return (<>
    <form id='my-form' onSubmit={handleSubmit(onSubmit)}>
        <div data-aos='fade-right' data-aos-delay='100' className="overflow-hidden mt-8 mb-4 w-[90vh] mx-auto bg-gray-100 rounded-lg border border-gray-300 dark:bg-gray-700 dark:border-gray-600">
            <label htmlFor="name" className="block mb-2 text-sm font-medium text-gray-900 dark:text-gray-300"></label>
            <input {...register('name', { required: true })} type="text" id="name" className="mb-2 radius block p-2 w-full text-gray-900 bg-gray-50 rounded-lg border-gray-300 sm:text-xs dark:bg-gray-800 dark:placeholder-gray-400 dark:text-white" minLength={3} placeholder="Your Name" />
            {errors.name  && <p className='text32'>Name is required. Minimum length should be 3</p>}
            <div className="py-2 px-4 bg-white rounded-t-lg dark:bg-gray-800" >
                <label htmlFor="comment" className="sr-only">Your comment</label>
                <textarea {...register('comment', { required: true })} id="comment" rows="4" minLength={5} className="px-0 w-full text-sm  text-gray-900 bg-white border-0 dark:bg-gray-800 focus:ring-0 dark:text-white dark:placeholder-gray-400" placeholder="Write a comment..."></textarea>
                {errors.comment && <p className='text32'>Minimum Comment length should be 5</p>}
            </div>
            <div className="flex justify-between items-center py-2 px-3 border-t dark:border-gray-600">
                <button onClick={notify} type="submit" data-aos='fade-up' data-aos-delay='400' className="btnz inline-flex items-center py-2.5 px-4 text-xs font-medium text-center text-white bg-blue-700 rounded-lg focus:ring-4 focus:ring-blue-200 dark:focus:ring-blue-900 hover:bg-blue-800">
                    Post comment
                </button>
            </div>
        </div>
    </form>
    <p data-aos='fade-left' data-aos-delay='700' className="h-[8vh] w-[70vh] m-auto text-xs text-gray-500 dark:text-gray-400">Remember, contributions to this topic should follow our <a href="#" className="text-blue-600 dark:text-blue-500 hover:underline">Community Guidelines</a>.</p>
</>
);

}

Answer №1

Trying to

access the name property of a comment object as comment.name or comment[0].name directly within JSON.stringify(comment)
will not work because JSON.stringify converts JSON data into a string format. If you want to retrieve the value of comment.name, you should avoid using JSON.stringify and simply refer to it as comment.name or comment[0].name

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

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

Having trouble with the containerElement in React material-ui's MenuItem component?

I'm having an issue with the code below: <MenuItem primaryText="home" containerElement={<Link to="/" />} /> Despite following discussions on other platforms like this one Material UI Menu using routes, adding the containerElement prop to ...

NextAuth.js in conjunction with nextjs version 13 presents a unique challenge involving a custom login page redirection loop when using Middleware - specifically a

I am encountering an issue with NextAuth.js in Nextjs version 13 while utilizing a custom login page. Each time I attempt to access /auth/signin, it first redirects to /login, and then loops back to /auth/signin, resulting in a redirection loop. This probl ...

Outdated state variable value recorded in the log

I am facing an issue where the logged value of the state variable 'count' is always zero, even after clicking the button to update it. The logging function is triggered by a setInterval function within the useEffect hook. Is there a reason why t ...

Adjusting Autocomplete input with react-hook-form and Material-UI

I am currently working with two Autocomplete fields. My objective is to update the value of the second field based on the value selected in the first field. However, I am encountering an issue where when I attempt to send the new value to the "setValue" f ...

Is the "node_modules" directory taking up too much space?

After running npx create-react-app, a node-modules folder is generated, which can be quite large at over 150 mb. I don't want this heavy folder to be created each time I start a new React project. Is there a way to avoid this issue and use React witho ...

Expo does not support playing audio files from assets

import AlphService from './AlphService'; export default class MyClass extends React.Component { alphService; constructor(props) { super(props); alphService = new AlphService(); this.state = alphService.getState(); } componentWillMount( ...

Display an array containing date objects in a dropdown menu for users to select from

I am working with an API call that returns an array of objects. Each object in the array contains a date or timestamp in ISO format. Right after my render() method, I have the following code snippet: const pickerItems = this.props.currentData.trips.map(t ...

Error: Unable to access the 'CodeMirror' property of null due to type mismatch

Encountering an issue with my NextJS (13) app. Chrome is throwing the following error: TypeError: Cannot read properties of null (reading 'CodeMirror') This error occurs every time I enter data in any input field within the app, although everyt ...

Leveraging React Hooks' useEffect to trigger a prop callback function defined with useCallback

Currently, I am working on developing a versatile infinite scrolling feature using React Hooks along with the ResearchGate React Intersection Observer. The main concept revolves around a parent passing down a mapped JSX array of data and a callback functio ...

Tips for featuring the latest blog post at the top of a NextJS blog

I have a website built on Next JS with a blog page. The setup is correct, where the /blog page displays content based on slugs. Currently, new blog posts are appearing at the bottom of the page, under older ones. I want to reverse this so that when a new p ...

What is the best way to make changes to the DOM when the state undergoes a

I've programmed the box container to adjust dynamically based on input changes. For instance, if I entered 1, it will generate one box. However, if I modify the input to 2, it mistakenly creates 3 boxes instead of just 2. import React from 'rea ...

How to horizontally align Material-UI elements in ReactJS

My goal is to create a user-friendly form where respondents can input answers to questions and select one as the preferred option by using a radio button. However, I'm facing an issue where Material-UI displays each element on its own line. This is t ...

Tips for preserving the Mobile Stepper's current state when the next button is clicked

To maintain the progress state of the Mobile Stepper, even when a user logs out and logs back in, it is crucial to save the current position. The goal is for the user to resume from where they left off, such as at 2% completion instead of starting over at ...

Using fast refresh in Next.js is leading to a fetch error when integrated with Express.js

When trying to fetch data from my API, I encountered an error due to fast refresh in Next.js. It seems that req.params only work once because of a bug with Next.js's fast refresh feature. Do you know of any solutions or alternative ways to retrieve th ...

Transforming three items into an array with multiple dimensions

There are 3 unique objects that hold data regarding SVG icons from FontAwesome. Each object follows the same structure, but the key difference lies in the value of the prefix property. The first object utilizes fab as its prefix, the second uses far, and t ...

Trouble with Moment.js - Unable to update date to "pt-br" (ReactJS)

I am currently developing a calendar in Portuguese using ReactJS. Even though it seems like a simple task, I am facing an issue trying to display the dates in Portuguese (Brazil) using the "moment.js" library. I have already attempted the following code: ...

The value is not getting set after calling React Hook UseState

I am currently working on a React component that handles payment processing. There is a part of my code where I utilize the useEffect hook alongside useState to set certain values. Check out the code snippet below: React.useEffect(()=>{ axiosFetch ...

Navigating with React-router can sometimes cause confusion when trying

I'm having trouble with my outlet not working in react-router-dom. Everything was fine with my components until I added the Outlet, and now my navigation component isn't showing even though other components are rendering. import Home from ". ...

Utilizing lazy loading to import local JSON data in Next.js

I currently have a JSON file stored locally in my project, which is an array with over 200 items. For example, the file is named data.js const data = [ { title: 1 }, { title: 2 }, ... { title: 200 } ]; Here is how I import it i ...

Having issues with stripe payments in my ReactJS application

I've encountered an issue while attempting to process a credit card payment using Stripe. Here's the code snippet I'm currently working with: import StripeCheckout from "react-stripe-checkout" // import confirmPayment from 'st ...