React useState boolean not updating

I am trying to create a custom toast to show error notification.
Toast visibility is depends on the isShowed from the props.

export type ToastProps = {
  color: 'error' | 'success' | 'warning';
  message: string;
  isShowed: boolean;
};

const Toast = (props: ToastProps) => {
  const { color, message, isShowed } = props;

  const [showed, setShowed] = useState(false);

  console.log(isShowed, showed);

  useEffect(() => {
    if (isShowed) {
      setShowed(true);
    } else {
      setShowed(false);
    }
  }, [isShowed]);

  return (
    <div
      className="toast-notification-wrapper"
      style={{
        position: 'fixed',
        top: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 9999,
        padding: '15px',
        borderRadius: '5px',
        transition: 'all 0.3s ease-out',
        opacity: showed ? 1 : 0,
        pointerEvents: showed ? 'auto' : 'none',
        display: 'flex',
        justifyContent: 'space-between',
        minWidth: '150px',
        backgroundColor:
          color === 'error'
            ? '#dc3545'
            : color === 'success'
            ? '#28a745'
            : '#ffc107',
      }}
    >
      <p style={{ margin: 0, color: 'white', fontSize: '15px', lineHeight: 1 }}>
        {message}
      </p>
      <span
        style={{
          cursor: 'pointer',
          display: 'flex',
          alignContent: 'center',
          justifyContent: 'center',
          marginLeft: '30px',
        }}
        onClick={() => {
          setShowed(!isShowed);
        }}
      >
        <FontAwesomeIcon
          icon={faClose}
          style={{ color: 'white', fontSize: '15px' }}
        />
      </span>
    </div>
  );
};

This is my toast components

const Login = (props: { isCompleted: boolean; isLoggedIn: boolean }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const navigate = useNavigate();
  const [toast, setToast] = useState({
    isShowed: false,
    color: 'error',
    message: 'failed',
  } as ToastProps);

  const { isCompleted, isLoggedIn } = props;

  if (isCompleted === false) {
    return null;
  }

  if (isLoggedIn) {
    navigate('/');
  }

  const togglePasswordVisibility = () => {
    setShowPassword(showPassword ? false : true);
  };

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    try {
      await login({ username, password });

      window.location.href = '/';
    } catch (error: any) {
      setToast({
        isShowed: true,
        color: 'error',
        message:
          error.response.data?.message ||
          'Unexpected Error. Please try again later',
      });
    }
  };

  return (
    <div className="login-form">
      <Toast
        isShowed={toast.isShowed}
        color={toast.color}
        message={toast.message}
      ></Toast>
      <div className="login-form-container">
        <h1>Login</h1>
        <form onSubmit={handleSubmit}>
          <div className="form-row">
            <label>Username</label>
            <input
              type="text"
              placeholder="Enter your username"
              required={true}
              onChange={e => setUsername(e.target.value)}
            ></input>
          </div>

          <div className="form-row">
            <label>Password</label>
            <input
              type={showPassword ? 'text' : 'password'}
              placeholder="********"
              required={true}
              onChange={e => setPassword(e.target.value)}
            ></input>
            <span
              onClick={togglePasswordVisibility}
              style={{
                position: 'absolute',
                right: '20px',
                top: 'calc(50% + 12px)',
                fontSize: '13px',
                transform: 'translateY(-50%)',
                cursor: 'pointer',
              }}
            >
              <FontAwesomeIcon
                icon={showPassword ? faEyeSlash : faEye}
                style={{ color: 'black' }}
              />
            </span>
          </div>

          <div className="button-wrapper">
            <button value={'Login'}>Login</button>
          </div>
        </form>
      </div>
    </div>
  );
};
const Login = (props: { isCompleted: boolean; isLoggedIn: boolean }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const navigate = useNavigate();
  const [toast, setToast] = useState({
    isShowed: false,
    color: 'error',
    message: 'failed',
  } as ToastProps);

  const { isCompleted, isLoggedIn } = props;

  if (isCompleted === false) {
    return null;
  }

  if (isLoggedIn) {
    navigate('/');
  }

  const togglePasswordVisibility = () => {
    setShowPassword(showPassword ? false : true);
  };

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    try {
      await login({ username, password });

      window.location.href = '/';
    } catch (error: any) {
      setToast({
        isShowed: true,
        color: 'error',
        message:
          error.response.data?.message ||
          'Unexpected Error. Please try again later',
      });
    }
  };

  return (
    <div className="login-form">
      <Toast
        isShowed={toast.isShowed}
        color={toast.color}
        message={toast.message}
      ></Toast>
      <div className="login-form-container">
        <h1>Login</h1>
        <form onSubmit={handleSubmit}>
          <div className="form-row">
            <label>Username</label>
            <input
              type="text"
              placeholder="Enter your username"
              required={true}
              onChange={e => setUsername(e.target.value)}
            ></input>
          </div>

          <div className="form-row">
            <label>Password</label>
            <input
              type={showPassword ? 'text' : 'password'}
              placeholder="********"
              required={true}
              onChange={e => setPassword(e.target.value)}
            ></input>
            <span
              onClick={togglePasswordVisibility}
              style={{
                position: 'absolute',
                right: '20px',
                top: 'calc(50% + 12px)',
                fontSize: '13px',
                transform: 'translateY(-50%)',
                cursor: 'pointer',
              }}
            >
              <FontAwesomeIcon
                icon={showPassword ? faEyeSlash : faEye}
                style={{ color: 'black' }}
              />
            </span>
          </div>

          <div className="button-wrapper">
            <button value={'Login'}>Login</button>
          </div>
        </form>
      </div>
    </div>
  );
};

and this is my login form components

The toast notification worked the first time when error event triggerd.
But when the error occurred again, the toast remained invisible.
When I use the console.log to check the state, the isShowed from props is true, but the showed is false.
Please help me. Thanks in advance.

3

remove useEffect block and showed state from Toast component, use following ToastProps

export type ToastProps = {
  color: 'error' | 'success' | 'warning';
  message: string;
  handleCloseToast: ()=>void
};

use this handleCloseToast function to close toast

and based on your toast state in parent, use following Toast props

<Toast
        handleCloseToast={() => setToast(prev => ({...prev,isShowed:false})}
        color={toast.color}
        message={toast. Message}
 ></Toast>

This is just code form of what @IdrisSelimi was explaining

Update:

I changed the useEffect to listen to props value changing instead of isShowed

useEffect(() => {
    if (isShowed) {
      setShowed(true);

      setTimeout(() => {
        setShowed(false);
      }, 3000);
    }
  }, [props]);

The previous version listened for changes in isShowed, but since the value was changing in props, so the data was not updating in useEffect dependency array.

Your useEffect code is off. It triggers on component mount and each time this component re-renders. Each time isShowed updates your useEffect updates it again but to the same value which triggers a re-render which triggers useEffect again, which is a bad infinite loop. You could just get rid of the useEffect and call your setter function from within some event like onClick or from a callback in a function, depending on how you wanna implement it.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

React useState boolean not updating

I am trying to create a custom toast to show error notification.
Toast visibility is depends on the isShowed from the props.

export type ToastProps = {
  color: 'error' | 'success' | 'warning';
  message: string;
  isShowed: boolean;
};

const Toast = (props: ToastProps) => {
  const { color, message, isShowed } = props;

  const [showed, setShowed] = useState(false);

  console.log(isShowed, showed);

  useEffect(() => {
    if (isShowed) {
      setShowed(true);
    } else {
      setShowed(false);
    }
  }, [isShowed]);

  return (
    <div
      className="toast-notification-wrapper"
      style={{
        position: 'fixed',
        top: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        zIndex: 9999,
        padding: '15px',
        borderRadius: '5px',
        transition: 'all 0.3s ease-out',
        opacity: showed ? 1 : 0,
        pointerEvents: showed ? 'auto' : 'none',
        display: 'flex',
        justifyContent: 'space-between',
        minWidth: '150px',
        backgroundColor:
          color === 'error'
            ? '#dc3545'
            : color === 'success'
            ? '#28a745'
            : '#ffc107',
      }}
    >
      <p style={{ margin: 0, color: 'white', fontSize: '15px', lineHeight: 1 }}>
        {message}
      </p>
      <span
        style={{
          cursor: 'pointer',
          display: 'flex',
          alignContent: 'center',
          justifyContent: 'center',
          marginLeft: '30px',
        }}
        onClick={() => {
          setShowed(!isShowed);
        }}
      >
        <FontAwesomeIcon
          icon={faClose}
          style={{ color: 'white', fontSize: '15px' }}
        />
      </span>
    </div>
  );
};

This is my toast components

const Login = (props: { isCompleted: boolean; isLoggedIn: boolean }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const navigate = useNavigate();
  const [toast, setToast] = useState({
    isShowed: false,
    color: 'error',
    message: 'failed',
  } as ToastProps);

  const { isCompleted, isLoggedIn } = props;

  if (isCompleted === false) {
    return null;
  }

  if (isLoggedIn) {
    navigate('/');
  }

  const togglePasswordVisibility = () => {
    setShowPassword(showPassword ? false : true);
  };

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    try {
      await login({ username, password });

      window.location.href = '/';
    } catch (error: any) {
      setToast({
        isShowed: true,
        color: 'error',
        message:
          error.response.data?.message ||
          'Unexpected Error. Please try again later',
      });
    }
  };

  return (
    <div className="login-form">
      <Toast
        isShowed={toast.isShowed}
        color={toast.color}
        message={toast.message}
      ></Toast>
      <div className="login-form-container">
        <h1>Login</h1>
        <form onSubmit={handleSubmit}>
          <div className="form-row">
            <label>Username</label>
            <input
              type="text"
              placeholder="Enter your username"
              required={true}
              onChange={e => setUsername(e.target.value)}
            ></input>
          </div>

          <div className="form-row">
            <label>Password</label>
            <input
              type={showPassword ? 'text' : 'password'}
              placeholder="********"
              required={true}
              onChange={e => setPassword(e.target.value)}
            ></input>
            <span
              onClick={togglePasswordVisibility}
              style={{
                position: 'absolute',
                right: '20px',
                top: 'calc(50% + 12px)',
                fontSize: '13px',
                transform: 'translateY(-50%)',
                cursor: 'pointer',
              }}
            >
              <FontAwesomeIcon
                icon={showPassword ? faEyeSlash : faEye}
                style={{ color: 'black' }}
              />
            </span>
          </div>

          <div className="button-wrapper">
            <button value={'Login'}>Login</button>
          </div>
        </form>
      </div>
    </div>
  );
};
const Login = (props: { isCompleted: boolean; isLoggedIn: boolean }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const navigate = useNavigate();
  const [toast, setToast] = useState({
    isShowed: false,
    color: 'error',
    message: 'failed',
  } as ToastProps);

  const { isCompleted, isLoggedIn } = props;

  if (isCompleted === false) {
    return null;
  }

  if (isLoggedIn) {
    navigate('/');
  }

  const togglePasswordVisibility = () => {
    setShowPassword(showPassword ? false : true);
  };

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    try {
      await login({ username, password });

      window.location.href = '/';
    } catch (error: any) {
      setToast({
        isShowed: true,
        color: 'error',
        message:
          error.response.data?.message ||
          'Unexpected Error. Please try again later',
      });
    }
  };

  return (
    <div className="login-form">
      <Toast
        isShowed={toast.isShowed}
        color={toast.color}
        message={toast.message}
      ></Toast>
      <div className="login-form-container">
        <h1>Login</h1>
        <form onSubmit={handleSubmit}>
          <div className="form-row">
            <label>Username</label>
            <input
              type="text"
              placeholder="Enter your username"
              required={true}
              onChange={e => setUsername(e.target.value)}
            ></input>
          </div>

          <div className="form-row">
            <label>Password</label>
            <input
              type={showPassword ? 'text' : 'password'}
              placeholder="********"
              required={true}
              onChange={e => setPassword(e.target.value)}
            ></input>
            <span
              onClick={togglePasswordVisibility}
              style={{
                position: 'absolute',
                right: '20px',
                top: 'calc(50% + 12px)',
                fontSize: '13px',
                transform: 'translateY(-50%)',
                cursor: 'pointer',
              }}
            >
              <FontAwesomeIcon
                icon={showPassword ? faEyeSlash : faEye}
                style={{ color: 'black' }}
              />
            </span>
          </div>

          <div className="button-wrapper">
            <button value={'Login'}>Login</button>
          </div>
        </form>
      </div>
    </div>
  );
};

and this is my login form components

The toast notification worked the first time when error event triggerd.
But when the error occurred again, the toast remained invisible.
When I use the console.log to check the state, the isShowed from props is true, but the showed is false.
Please help me. Thanks in advance.

3

remove useEffect block and showed state from Toast component, use following ToastProps

export type ToastProps = {
  color: 'error' | 'success' | 'warning';
  message: string;
  handleCloseToast: ()=>void
};

use this handleCloseToast function to close toast

and based on your toast state in parent, use following Toast props

<Toast
        handleCloseToast={() => setToast(prev => ({...prev,isShowed:false})}
        color={toast.color}
        message={toast. Message}
 ></Toast>

This is just code form of what @IdrisSelimi was explaining

Update:

I changed the useEffect to listen to props value changing instead of isShowed

useEffect(() => {
    if (isShowed) {
      setShowed(true);

      setTimeout(() => {
        setShowed(false);
      }, 3000);
    }
  }, [props]);

The previous version listened for changes in isShowed, but since the value was changing in props, so the data was not updating in useEffect dependency array.

Your useEffect code is off. It triggers on component mount and each time this component re-renders. Each time isShowed updates your useEffect updates it again but to the same value which triggers a re-render which triggers useEffect again, which is a bad infinite loop. You could just get rid of the useEffect and call your setter function from within some event like onClick or from a callback in a function, depending on how you wanna implement it.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật