Trouble with setting state in React using hooks

There appears to be an issue with the code below where the variable newName's state is not changing as expected.

import React, { useState } from 'react'

const App = () => {
    const [ persons, setPersons] = useState([
        { name: 'Arto Hellas' }
    ])
    const [ newName, setNewName ] = useState('')

    const textChangeHandler = (event)=>{
        event.preventDefault()
        setNewName(event.target.value) // WORKS FINE
    }

    const submitHandler = (event)=>{
        event.preventDefault()

        let temp = {name:newName}
        setNewName('')    //////////////////////////////////////// PROBLEM - doesnot set state!!
        console.log('tenp name is',temp.name)
        console.log('new name is',newName)
        setInterval(()=>console.log("Set Interval",newName), 1000)
    }

    return (
        <div>
            <h2>Phonebook</h2>
            <form onSubmit={submitHandler}>
                <div>
                    name: <input onChange={textChangeHandler}  />
                </div>
                <div>
                    <button type="submit" >add</button>
                </div>
            </form>
            <h2>Numbers</h2>
            {persons.map((person) => <Person key = {person.name} name={person.name}/> )}
        </div>
    )
}

const Person  = ({name})=> <p> {name} </p>

The function setNewName works correctly when typing in the input box, updating the name accordingly. However, upon clicking the submit button, setNewName fails to update the name. Despite calling setNewName, the name remains unchanged. I attempted using a setInterval to address any asynchronous behavior in JavaScript, but even then the updated newName was not reflected.

How can this problem be identified and resolved?

Your help is greatly appreciated!

Answer №1

Upon inspecting the submitHandler function, you'll observe that the name itself remains unaltered; it stays empty in its original state. React only triggers a reload when there is a change in the state value as illustrated below:

const submitHandler = (event)=>{
        event.preventDefault()

        let temp = {name:newName}
        //setNewName('')    // There is no change in value here... line removed
        setNewName(temp.name) // Name changed to new one from temp
        console.log('temporary name is',temp.name)
        console.log('new name is',newName)
        setInterval(()=>console.log("Set Interval",newName), 1000)
    }

Answer №2

It is important to note that setting a state is an asynchronous process. Avoid using scheduling functions such as setTimeout and setInterval to log the value of state.

Instead, utilize useEffect -

  useEffect(() => {
    console.log("The value is", newName);
  }, [newName]);

Your hook is functioning properly without any issues. You can view a demo on CodeSandbox to see everything in action.

Answer №3

When working with React, it's important to remember that setState is not synchronous for both class components and hooks. This means that you cannot rely on a new state being available immediately after setting it. To address this issue, consider revising the submitHandler function implementation.

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

A scenario in a Jasmine test where a function is invoked within an if statement

My coding dilemma involves a function: function retrieveNames() { var identifiers = []; var verifyAttribute = function (array, attr, value) { for (var i = 0; i < array.length; i++) { if (array[i][attr] === va ...

Interactive Image Component in React

I'm encountering an issue with my React code. import { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import RecipeService from "./RecipeService"; import RecipeProfileImg from "./Re ...

What is the best way to organize a flatlist for rendering?

I'm struggling with separating some flat-lists into different components. How can I arrange the rendering of the flat-list like the sample form (Picture "Sample UI")? I've tried, but it's not working correctly as it renders flat list A first ...

React: Introducing the latest router feature post-login

I'm facing an issue with the Router in React. After a successful login, I am changing the type state in Redux from 0 to 1. However, when I try to make a switch in my App file, I encounter an error. Warning: [react-router] You cannot change <Router ...

Error message stating that there is no property 'collection' in Firestore when using Firebase v9 modular syntax in Firebase Firestore

Working on a React application that makes use of Firebase Firestore for handling database operations, I recently upgraded to Firebase version 9 and adopted the modular syntax for importing Firebase services. Nevertheless, when attempting to utilize the co ...

Placing a new item following each occurrence of 'X' in React components

Currently, I am working with a React component that uses Bootstrap's col col-md-4 styles to render a list of items in three columns. However, I am facing an issue where I need to add a clearfix div after every third element to ensure proper display of ...

What is the advantage of not importing related modules?

As a newcomer to React, please excuse any novice questions I may have. I am currently utilizing npx create-react-app to develop a React app, but I'm unsure of the inner workings: Q1-If I were to throw an error in a component like so: import React, { ...

Encountered an issue while attempting npm install, with the error message "Error: Undefined variable standalone_static_library in binding.gyp" and node-sass chokidar error

I've been working on updating a Ruby on Rails and React project from 3 years ago. However, I encountered an issue while trying to npm install. $ npm install gyp: Undefined variable standalone_static_library in binding.gyp while trying to load binding ...

Can you explain the concepts of 'theme' and 'classes'?

Currently, I am working on a web application using React. I have chosen to incorporate the latest version of Material-UI for designing the user interface. During this process, I came across the demo examples provided by Material-UI (like ) In each demo ...

React Native Header Icon Not Showing on the Left Side

I'm brand new to react and currently working on a project where navigation is done through a hamburger menu. I haven't encountered any errors in my code, but for some reason, the hamburger menu icon isn't displaying as expected. Interestingl ...

Issue encountered: ENOENT - There is no file or directory located at the specified path for ... .steampath

I am encountering an issue while attempting to launch the development server on a React project that has been dormant for quite some time. After executing npm install and npm start, I encountered the following error message. Despite my efforts to manua ...

Having difficulty accessing the Material UI Icons

I encountered an issue when attempting to utilize Material UI icons - as soon as I added the icon component, an error occurred. https://i.stack.imgur.com/issmm.png For reference, you can find the code on CodeSandbox at the following link: https://codesand ...

Stylish hover effects displayed on disabled button using Styled Components

I am currently working on a button using Styled Components. However, even when the button is in a disabled state (:disabled), it still exhibits hover behavior that should not be present. I am wondering if there is a proper way to prevent hover effects when ...

A guide on crafting a test scenario for an AngularJS controller using the Jasmine framework

I recently created an angular module called userModule.js 'use strict'; angular.module('users', ['ngRoute','angular-growl','textAngular','ngMaterial','ngMessages','ngImgCrop', ...

Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

How can the required flag be integrated with rules validation in react-hook-form and material-ui (mui) for inputs?

Currently, I have implemented react-hook-forms for handling form functionality and validation in our application. On the other hand, we are utilizing MUI/Material-UI as our component library. One issue that arises is that MUI automatically adds a * to inpu ...

What is the best way to eliminate a specific value within a flatmap?

This is the flatMap: const choices = names.flatMap( (item) => item.name + " - " + item.size + "- " + item.category ); console.log(choices): https://i.stack.imgur.com/MO4b1.png If the item.category is equal to S-XL, how can ...

I am struggling to apply custom CSS styles to the scrollbar within a Card component using MUI react

import React from "react"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/Ca ...