Home > front end >  hook state is not updating in function
hook state is not updating in function

Time:12-07

I tried to map over users and put them into a table row, then in the map func i gave each row onClick that send each time diffrent property to the function.

    const [attackDetails, setAttackDetails] = useState('');
    const [alreadyShown, setAlreadyShown] = useState(false);

   const getTableMembers = (result) =>{
        let i = 1
        const members = result.map((member, key) =>{
            return(
                <tr key= {key} className='table__content-table__row' onClick={() => showAttackOptions(member)}>
                    <td>{i  }</td>
                    <td>{member.NickName}</td>
                    <td>{member.Power.Soldiers.Ammount}</td>
                    <td>{member.alliance}</td>
                    <td>Status</td>
                </tr>
            )})
        setMembers(members);
    }

Then I simply tried to toggle my kind of like dropbox by using state:

    const showAttackOptions = (prop) => {
        if(alreadyShown) {
            setAttackDetails('')
            setAlreadyShown(false)
        }else{
            setAttackDetails(<h1>{prop.NickName}</h1>)
            setAlreadyShown(true);
            
        }
    }

but the state "alreadyShown" remains undefined (false).

ty for your help.

CodePudding user response:

You need to use the hook "useEffect" to change the alreadyShown state (constructing the logic about your useState) and after you need to verify your return.

  • Related