bacco2
bacco2

Reputation: 360

React state, Onclick will not fire first time.. only second

import React , {useState} from 'react';

function Test() {
    
    const [addtolist, Setaddtolist] = useState();      
    
    const Onclick = () =>{
        Setaddtolist('Button Clicked');
       
        //I need the state in this function
        console.log(addtolist)
    }

    // I can't console.log(addtolist) here
    

      return (
       <div>
        <button onClick={() => Onclick()}>Test Button</button>
       </div>
      );
    }
    
    export default Test;
    

Why wont the addtolist state update on the first click? It will fire second time, but not first why(undefined)?

Upvotes: 0

Views: 1366

Answers (2)

Diceros
Diceros

Reputation: 83

I see an issue here with the function you are passing to onClick. When you call this function:

 const Onclick = () =>{
        Setaddtolist('Button Clicked');
       
        //I need the state in this function
        console.log(addtolist)
    }

It will call everything you have between curly bracets. But then, you have put this onClick handler into another function:

onClick={() => Onclick()}

And this is causing the strange behaviour, because when this is called, it will return an onClick handler function you defined higher. It will not be called, just returned.

To fix this, I would simply define the button like this:

const Onclick = () =>{
        Setaddtolist('Button Clicked');
       
        //I need the state in this function
        console.log(addtolist)
        }

   return(
    <div>
        <button onClick={onClick}>Test Button</button>
    </div>);

It passes the whole function as it is to the onClick parameter, it will then be called when the button is clicked. No need to wrap it anymore.

Upvotes: 0

Ezequiel S. Sandoval
Ezequiel S. Sandoval

Reputation: 170

setState is an asynchronous action so what you are displaying is the first state of addtolist that is either null | undefined. If you want to actually see the current state you setted then use useEffect hook: useEffect(() => { console.log(addtolist); }, [addtolist])

Upvotes: 1

Related Questions