skip to Main Content

Why won’t this code which causes a variable called age to increase or decrease according to the pressing of certain buttons. But then it should also allow us see whatever is typed in the text box be displayed outside of it.

App.js

import {useState} from "react";
import './App.css';
function App() {
const [age, setAge] = useState(0);
const [inputValue, setInputValue] = useState("");

const increaseAge = () => {
setAge(age + 1);
};
const decreaseAge = () => {
    setAge(age - 1);
};
 const increaseAgeten = () => {
    setAge(age + 10);
 };
 const decreaseAgeten = () => {
    setAge(age - 10);
 };
const increaseAgehundred = () => {
    setAge(age + 100);
 };
 const decreaseAgehundred = () => {
    setAge(age - 100);
 };
const handleInputChange = (event) =>{setInputValue(event.target.value)}
return (
    <div className="App">
    
    <br></br>
    {age}
    <br></br>
    
    <button onClick={increaseAge}>+1</button>
    <button onClick={decreaseAge}>-1</button>
    <br></br>
    <button onClick={increaseAgeten}>+10</button>
    <button onClick={decreaseAgeten}>-10</button>
    <br></br>
    <button onClick={increaseAgehundred}>+100</button>
    <button onClick={decreaseAgehundred}>-100</button>
    <br></br>
    <input type="text" onChange = {handleInputChange}/>     
    </div>
  );
}


export default App;

The think the problem may be that useState is used twice

const [inputValue, setInputValue] = useState("");

This is from the tutorial https://youtu.be/f55qeKGgB_M?t=4693

2

Answers


  1. Chosen as BEST ANSWER

    I forgot to put {InputValue} after the input. Everything is working fine now. Thanks


  2. The problem is that you can’t mutate the state in React. So you can’t have it like this:

    const increaseAge = () => {
       setAge(age + 1);
    };
    

    Instead you should have something like that:

    const increaseAge = () => {
       const nextAge = age + 1
       setAge(nextAge);
    };
    

    Short explanation is, that React is comparing entities, and if you do this like you have in code, for React there was no change, but if you will provide new object it will recognize the change.

    It is really common mistake, you can read more about this issue on this blog post:
    https://www.joshwcomeau.com/react/common-beginner-mistakes/#mutating-state-2

    I generally recommend to follow Josh for React knowledge.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search