Using NextJS: Issue with updating Value in useState

In my current project, I am attempting to display a string that changes when a button is pressed in my NextJs application.

Here's the code snippet I am working with:

'use client'
import { useState } from 'react'

export default function Home() {

const [ currWord, setCurrWord ] = useState<string>('none');

return (
...
<p>{currWord}</p>
...
<button onClick={() => setCurrWord('changed')}>change</button>
...

)

}

When I click the button, the webpage and hence the string do not update. This issue persists even if the content is numeric. Initially, I tried implementing a function to change the word upon clicking the button, but it didn't work as expected. I'm puzzled by this since my approach seems similar to other examples I have come across.

Edit 1: For reference, I am using VSCode 1.76.2, Next.js 13 with the new app Folder and TypeScript version 5.1.0 (I also tested with version 4.6.3)

Answer №1

After incorporating a react fragment into your code, the view now displays perfectly as intended.
Give it a try and let me know what you think.

'use client'
import { useState } from 'react'

export default function HomePage() {

    const [currentText, setCurrentText] = useState<string>("default");

    return (
        <>
            <p>{currentText}</p>
            <button onClick={() => setCurrentText("modified")}>modify</button>
        </>
    )

}

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

Creating an Angular service that checks if data is available in local storage before calling an API method can be achieved by implementing a

I am currently working on developing an Angular service that can seamlessly switch between making actual API calls and utilizing local storage within a single method invocation. component.ts this.userService.getAllUsers().subscribe(data => { conso ...

Typescript UniqueForProp tool not working as expected

I've created a utility function called UniqueForProp that takes an array of objects and a specified property within the object. It then generates a union type containing all possible values for that property across the array: type Get<T, K> = K ...

I can't figure out why I'm getting the error message "Uncaught ReferenceError: process is not defined

I have a react/typescript app and prior to updating vite, my code checked whether the environment was development or production with the following logic: function getEnvironment(): "production" | "development" { if (process.env.NODE_E ...

Changing function arguments in TypeScript using the spread operator

Could the Tuple spreading syntax in Typescript be utilized to consolidate these function overloads? The challenge lies in the necessity to refactor the function arguments into new types. type Type = TString | TNumber type TString = { tag: 'string&apos ...

Unable to transfer object from Angular service to controller

I am currently utilizing a service to make a $http.get request for my object and then transfer it to my controller. Although the custom service (getService) successfully retrieves the data object and saves it in the responseObj.Announcement variable when ...

Encountering difficulties when compiling my Angular application

Currently, I am working with Angular 2. To include Bootstrap in my project, I utilized the node.js command prompt for installation. npm install ngx-bootstrap --save I made adjustments to the .csproj file in order to deploy my application on the server vi ...

Leverage the data populated by useEffect to conditionally use the SWR hook

Currently trying to resolve the issue raised in this query, and progress has been made. The API is returning the correct data and updating as expected. However, upon initial loading, useSWR is making requests to the API with all data being null. The data ...

Fixing prop passing issues in Vue.js components to prevent errors

My Vue-cli install with TypeScript is set up to render JSX using a boilerplate. However, I am facing an issue when trying to pass a property to the HelloWorld component. Here's what my code looks like: export default Vue.extend({ name: 'App&apo ...

After introducing 5 guard properties, the intersection of unions in Typescript breaks down

In TypeScript, I am attempting to create a class where properties are only accessible if another property has been checked on the class. This needs to be done in a generic manner to facilitate reuse across multiple classes. For instance, class Test { Fo ...

Something went wrong: "Server Error - No 'exports' main defined in package.json for C:chart ode_moduleschart.js"

I'm attempting to retrieve the time scale (x-axis) by employing the chartjs-adapter-date-fns adapter, but encountering the following error: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: C:\chart\node_modules\chart.js\package.json does n ...

I'm having trouble viewing the unique Google Map design on my application

I have recently customized Google maps following the guidelines in this documentation: https://developers.google.com/maps/documentation/javascript/styling For styling, I utilized the Cloud tool and opted for the available template instead of using JSON st ...

The current @next/swc version does not match with Next.js, with a detected version of 14.0.3 compared to Next.js' 13.5

Every time I attempt to launch my docker image, an error pops up indicating a mismatching @next/swc version. The error message mentions: "Mismatching @next/swc version, detected: 14.0.3 while Next.js is on 13.5.3." This results in an internal server error ...

React Typescript: exploring the power of dynamic types

Can dynamic typing be implemented? The JSON structure I am working with looks like this: { "fieldName": "Some text", "type": String, "inputType": "text" }, { "fieldName": "Some bool&q ...

The Redux state does not seem to update within the requestAnimationFrame function

After making updates to the Redux state, the component receives the updated state data, but not within the requestAnimationFrame function. For example, we can observe the updated state (backgroundMode) being logged near the top of the component declaratio ...

I'm curious if anyone has experimented with implementing TypeScript enums within AngularJS HTML pages

During my Typescript project, I defined an enum like this: enum Action { None = 0, Registering = 1, Authenticating = 2 }; In the controller, I declared a property named action as follows: class AuthService implements IAuthService { action: number; ...

Issues with CSS Styling not being applied properly on mobile devices in a React App deployed on Heroku

The Dilemma My React app is deployed on Heroku using create-react-app for bundling. The backend is a Node.js written in Typescript with node version 10.15.3. Locally, when I run the site using npm start, everything works perfectly. However, when I view t ...

Leverage the extended properties of Express.js's Request's generic arguments

I am currently working on extending the Request type to include a property that relies on the request body. However, I am facing an issue where the generic in catchAsync is not being correctly applied and always defaults to any instead of the specified gen ...

Creating React components with TypeScript: Defining components such as Foo and Foo.Bar

I have a react component defined in TypeScript and I would like to export it as an object so that I can add a new component to it. interface IFooProps { title:string } interface IBarProps { content:string } const Foo:React.FC<IFooProps> = ({ ...

Unable to locate module, encountered a webpack alias issue while using typescript and react

I'm currently in the process of setting up aliases in webpack. My goal is to make importing components in App.js easier by replacing: ./components/layout/Header/Header with: @components/layout/Header/Header This way, I can avoid potential issues w ...

When combining NextJS, Rollup, and yalc, an error may occur stating "Element type is invalid: expected a string (for built-in components) but got: undefined."

While working on creating a component library for React, I keep encountering the following error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forg ...