Roman Karpyshyn
Roman Karpyshyn

Reputation: 199

useState changed value just at first time

my hook useState change state just once, all the time i have 1. How can i fix it ?

 const My = () => {
    const [state,setState] = useState({
        count : 0
    })

    useEffect(() => {
        console.log(state);
      },[state]);

    return (
        <div>
            <h1>{state.count}</h1>
            <button onClick={()=> setState(prevState => ({
                ...prevState,
                count: +1
            }))}>Click</button>
        </div>
    );
};

Upvotes: 2

Views: 342

Answers (2)

Erik
Erik

Reputation: 188

There is a syntax error in your code: count: +1.

So, the quick fix is this:

const My = () => {
  const [state,setState] = useState({
    count : 0
  })

  useEffect(() => {
    console.log(state);
  }, [state]);

  return (
    <div>
      <h1>{state.count}</h1>
      <button onClick={()=> setState(prevState => ({
        ...prevState,
        count: prevState.count + 1
       }))}>Click</button>
    </div>
  );
};

However, your code can be simplified a lot. This will output the exact same thing:

const My = () => {
  const [count, setCount] = useState(0);

  console.log(state);

  return (
    <div>
      <h1>{state.count}</h1>
      <button onClick={()=> setCount(count + 1)}>Click</button>
    </div>
  );
};

Upvotes: 2

Mechanic
Mechanic

Reputation: 5380

Here is the problem ()=> setState(prevState => ({ ...prevState, count: +1 })) and can be fixed this way:

onClick={() =>
           setState(prevState => ({
             ...prevState,
             count: prevState.count+1
           }))
         }

Upvotes: 1

Related Questions