React State remains immutable when i try to show component onClick

Viewed 84

I have button with onClick function like this :

<button className="btn" onClick={(e) => handleClick(user._id, e)} >Edit</button>
const [show, setShow] = useState(false)


const handleClick = (id, e) => {
    e.preventDefault()
    setShow(!show)
    dispatch(getUser(id))}

/* And here rendering based on State */
{
  show ? renderUserData() : null
}

So, problem is that setShow(!show) inside the handleClick function does not work and state of show remains false, immutable. if handleClick function contains only setShow(!show) then this function working and toggling renderUserData(), but when it contains both dispatch(getUser(id)) and setShow(!show), state of show remains false all time,please help

1 Answers

try to remove the e.preventDefault() you can play around with your own data but the e.preventDefault() is not useful in buttons (if you have a form try to put it in the onSubmit of the form) but the final solution must look something like this:

import React, { useState } from "react";

export default function App() {
  const [show, setShow] = useState(false);

  const handleClick = (id, e) => {
    setShow(!show);
  };

  return (
    <>
      {show ? <h1>Data showed</h1> : null}
      <button className="btn" onClick={(e) => handleClick(e)}>
        Edit
      </button>
    </>
  );
}

Related