Is it possible for the button text to switch from Farewell to Greetings after two clicks?

There seems to be a strange issue in my React TS project - I have to click the button twice to switch the text from "Goodbye" to "Hello", but not the other way around. Any ideas why?

import { useState } from 'react' 

const ChangeTextButton = () => {

    const [buttonText, setButtonText] = useState("Click me!")
    var changedBefore = false;

    function changeText() {
        
        if (changedBefore) {
            setButtonText("Hello")
        } else {
            setButtonText("Goodbye")
        }
        
        changedBefore = !changedBefore
        return buttonText;
    }

    return(
        <button onClick={() => changeText()}>{buttonText}</button>
    );
}

export default ChangeTextButton;

Seems like there might be some issues with this code, but I'm still learning TypeScript and JS.

Answer №1

The reason for this issue is that the variable changedBefore gets reset to false after each rerender.

Initially starting as false, upon the first click, it changes the button text to "Goodbye" and triggers a rerender. This rerender resets the value back to false. On the next click, although the text changes to "Goodbye" again, since it's in the same state as the current one, there is no rerender triggered. This results in changedBefore being set to

true</code for the subsequent click, which finally changes the text to "Hello."</p>
<p>To avoid this behavior, utilizing <code>useState
or useRef for the changedBefore variable is recommended, like so:

import { useState } from 'react' 

const ChangeTextButton = () => {

    const [buttonText, setButtonText] = useState("Click me!")
    const [changedBefore, setChangedBefore] = useState(false);

    function changeText() {
        
        if (changedBefore) {
            setButtonText("Hello")
        } else {
            setButtonText("Goodbye")
        }
        
        setChangedBefore(cb => !cb)
    }

    return(
        <button onClick={() => changeText()}>{buttonText}</button>
    );
}

export default ChangeTextButton;

Demo: https://stackblitz.com/edit/react-wuulup?file=src%2FApp.js

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

I'm having trouble with my Typescript file in Vscode - every time I try to edit the css code, all the text turns red. Can someone

Check out this visual representation: [1]: https://i.stack.imgur.com/9yXUJ.png Followed by the corresponding code snippet. export const GlobalStyle = createGlobalStyle` html { height: 100%; } body { background-image: url(${BGImage}); ba ...

Unable to set up enzyme adapter

Currently, I am in the process of setting up the enzyme adapter for testing purposes. The code snippet that I have is quite straightforward: import * as enzyme from 'enzyme'; import * as Adapter from 'enzyme-adapter-react-16'; enzyme. ...

Issue with Angular 2 Routing: Unable to find a matching route

Currently, I'm in the process of developing an Angular 2+ application that requires routing. One of the requirements is for the color scheme of the entire app to change based on a URL parameter input. In my app.module.ts file, I have the following co ...

Leverage the spread operator (or an equivalent method) to transfer all attributes from a solitary mixin

When working with the example below, my goal is to pass only the properties of MyMixedInProps to MyChildComponent using a method similar to the spread operator ({...props}). In my specific scenario, MyMixedInProps is defined in a third-party library (whic ...

Leverage the TypeScript Compiler API to verify whether an interface property signature permits the value of undefined (for example, prop1?:

Currently, I am utilizing the TypeScript Compiler API to extract Interface information in order to generate database tables. The process is functioning effectively, however, I am seeking a method to determine if certain fields are nullable, or as it is phr ...

Encountered an error trying to access properties that are undefined while working with Ionic Angular, specifically having trouble reading the 'update

As someone who is new to building ionic angular applications (coming from a PHP background), I am currently facing an issue. I have a page with the following code: export class LicencesTabPage implements OnInit { public licencesData: any[] | void; co ...

Issue: NG0204: Unable to find solutions for all parameters in NzModalRef: (?, ?, ?)

I'm currently working on an Angular project utilizing the NZ-Zorro library, and I'm encountering difficulty understanding which parameters are causing issues with NzModalRef when attempting to run the test code coverage. The error message display ...

How can I customize a currency directive in AngularJS using filters?

My goal is to enhance user experience by allowing input in custom currency values like '1.5M' instead of 1500000, and '1B' instead of 1000000000 on an input form dealing with large numbers. To achieve this, I've created a FormatSer ...

Rearrange component positions without triggering a re-render

I am currently developing a React page for a chat application with a UI design similar to the image provided (Please disregard the black box for sensor info). https://i.sstatic.net/ErVN8.png Within this page, I have created two separate components: The ...

Warning: Node encountering unexpected Unhandled Promise Rejection ERROR

I've encountered a problem in my code that is triggering an UnhandledPromiseRejectionWarning in Node, but I'm struggling to understand the root cause. Here's a simplified version of the code: export class Hello { async good(): Promise<s ...

"Adjusting the position of an Ionic Menu on-the-fly

As I strive to update the Ionic 3 Menu side dynamically when the user changes the language, a challenge arises for RTL languages where the menu needs to be on the right instead of the default left. To tackle this issue, I have subscribed to the TranslateS ...

Best practices for using useEffect to fetch data from an API_FETCH in a certain condition

When retrieving state from an API using Zustand within a useEffect function, what is the recommended approach to do so? Currently, my implementation is quite straightforward: export interface ModeState{ modes: Mode[]; fetchModes: () => void; } expo ...

Can an attribute be assigned to an Angular host element without specifying a value?

Exploring the concept of host binding on the input element's readonly attribute, aiming to add the attribute without assigning any value. Even though HTML specifications state that assigning a value may not make a difference as long as the attribute i ...

Guide to creating a setter for an array property in Angular 2 (Typescript) that will be filled by the view

Question: private _secretQuestions: {question: number, answer: string}[]; Within my HTML, I have three select boxes representing questions, each with a corresponding input box for answers. My goal is to map the selected questions and input values to the ...

Verification based on conditions for Angular reactive forms

I am currently learning Angular and working on creating a reactive form. Within my HTML table, I have generated controls by looping through the data. I am looking to add validation based on the following cases: Upon page load, the Save button should be ...

What is causing the issue of URL parameters becoming undefined when performing service injection in the app component?

When working with a service that reads parameters from the URL, everything seems to be functioning properly until attempting to inject the service into the constructor of the app.component.ts file or trying to call a service method from the app.component.t ...

In TypeScript, encountering an unanticipated intersection

In my "models" registry, whenever I select a model and invoke a method on it, TypeScript anticipates an intersection of parameters across all registered models. To demonstrate this issue concisely, I've created a dummy method called "getName". expor ...

Definition of Angular 2 File

I have developed a custom Gantt chart library using D3 in vanilla JavaScript. Now, I am trying to integrate it into my Angular 2 application. After installing D3 via npm and adding the necessary type files and the Gantt chart module to node_modules, I enco ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

Verify in Typescript if there is at least one value supplied

Looking for a solution: function takeOneOfOrThrow(firstOptionalVariable : string | undefined, secondOptionalVariable : string | undefined) { let result : string; if (!firstOptionalVariable && !secondOptionalVariable) { throw new E ...