Child Component function firing before parent state is updated

I have been trying to make a dropdown component that is reusable and decided to put 2 inputs in there so I can validate the range of value. The validation happens but the state passed as a prop does not update before setIsOpen function is fired.

// states
const { data, error, isLoading } = useRegionsData();
  const {
    filters,
    setFilters,
  } = useFilter();

  const [localFilters, setLocalFilters] = useState<FilterValues>({
    price: { min: '', max: '' },
    region: [],
    area: { min: '', max: '' },
    bedroom: '',
  });

  const [localErrors, setLocalErrors] = useState<FilterErrors>({
    area: false,
    bedroom: false,
    price: false,
  });

  console.log(localFilters.price);
  console.log(localErrors);

  /* this useffect initilizes local filter regions to look like a object {id,name,checked} */
  useEffect(() => {
    const savedFilters = localStorage.getItem('filters');
    if (savedFilters) {
      const filterData = JSON.parse(savedFilters) as FilterValues;
      setLocalFilters(filterData);
    } else if (data) {
      const regionData = data.map((region) => ({
        id: region.id,
        name: region.name,
        checked: false,
      }));

      setLocalFilters((prevState) => ({
        ...prevState,
        region: regionData,
      }));
    }
  }, [data, setLocalFilters]);

// update functions
const handlePriceConfirmClick = () => {
    if (!localFilters.price.min || !localFilters.price.max) {
      setLocalErrors((prevErrors) => ({
        ...prevErrors,
        price: true,
      }));

      return;
    }

    if (Number(localFilters.price.min) > Number(localFilters.price.max)) {
      setLocalErrors((prevErrors) => ({
        ...prevErrors,
        price: true,
      }));

      return;
    }

    // If everything is okay, submit the form
    setFilters(localFilters);
    localStorage.setItem('filters', JSON.stringify(localFilters));
  };

  

  const handlePriceChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;

    setLocalFilters((prevState) => {
      const updatedPrice = {
        ...prevState.price,
        [name]: value,
      };

      const minPrice = Number(updatedPrice.min);
      const maxPrice = Number(updatedPrice.max);

      const hasError = minPrice >= maxPrice;
      setLocalErrors((prevErrors) => ({
        ...prevErrors,
        price: hasError,
      }));

      return {
        ...prevState,
        price: updatedPrice,
      };
    });
  };

so what i am interested in is NewDropdown component when handleSubmit happends the error should stop the function from compleating but for some reason the previous value of state is passed to it.

// dropdown component where error is suppose to decide if it closes it
import { useEffect, useRef, useState } from 'react';
import upIcon from '../../assets/images/DropdownIconUp.svg';
import downIcon from '../../assets/images/DropdownIconDown.svg';
import Button from '../button/Button';

type Props = {
  children: React.ReactNode;
  buttonText: string;
  dropdownTitle: string;
  onSubmit: () => void;
  error?: boolean;
};

const NewDropdown = ({
  children,
  dropdownTitle,
  buttonText,
  onSubmit,
  error = false,
}: Props) => {
  const [isOpen, setIsOpen] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  /* content outside of dropdown will trigger setIsOpen(false) */
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        buttonRef.current &&
        !buttonRef.current.contains(event.target as Node) &&
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const handleClick = () => {
    setIsOpen((prevState) => !prevState);
  };

  const handleSubmit = () => {
    console.log('err', error);
    onSubmit();
    if (!error) {
      setIsOpen(false);
    }
  };

  return (
    <div className='relative'>
      <button
        ref={buttonRef}
        onClick={handleClick}
        className={`rounded-md py-2 px-[14px] flex justify-center items-center gap-1 text-text font-medium ${
          isOpen ? 'bg-selected' : 'bg-transparent'
        }`}
      >
        {buttonText}
        <span>
          <img
            src={isOpen ? upIcon : downIcon}
            alt={isOpen ? 'menu open icon' : 'menu closed icon'}
          />
        </span>
      </button>
      {isOpen && (
        <div
          ref={dropdownRef}
          className='absolute bottom-0 transform translate-y-full left-0 p-6 rounded-[10px] border border-border bg-white z-20'
        >
          <p className='font-firago font-medium mb-6'>{dropdownTitle}</p>
          {children}
          <div className='flex justify-end mt-[32px]'>
            <Button
              className='bg-primary text-white py-2 px-[14px] rounded-lg font-firago font-medium transition-colors duration-200 ease-linear hover:bg-primaryHover'
              onClick={handleSubmit}
            >
              არჩევა
            </Button>
          </div>
        </div>
      )}
    </div>
  );
};

export default NewDropdown;

My guess was that the state was old so I used let variable instead but with that the error does not update at all because it is not a react state

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

Child Component function firing before parent state is updated

I have been trying to make a dropdown component that is reusable and decided to put 2 inputs in there so I can validate the range of value. The validation happens but the state passed as a prop does not update before setIsOpen function is fired.

// states
const { data, error, isLoading } = useRegionsData();
  const {
    filters,
    setFilters,
  } = useFilter();

  const [localFilters, setLocalFilters] = useState<FilterValues>({
    price: { min: '', max: '' },
    region: [],
    area: { min: '', max: '' },
    bedroom: '',
  });

  const [localErrors, setLocalErrors] = useState<FilterErrors>({
    area: false,
    bedroom: false,
    price: false,
  });

  console.log(localFilters.price);
  console.log(localErrors);

  /* this useffect initilizes local filter regions to look like a object {id,name,checked} */
  useEffect(() => {
    const savedFilters = localStorage.getItem('filters');
    if (savedFilters) {
      const filterData = JSON.parse(savedFilters) as FilterValues;
      setLocalFilters(filterData);
    } else if (data) {
      const regionData = data.map((region) => ({
        id: region.id,
        name: region.name,
        checked: false,
      }));

      setLocalFilters((prevState) => ({
        ...prevState,
        region: regionData,
      }));
    }
  }, [data, setLocalFilters]);

// update functions
const handlePriceConfirmClick = () => {
    if (!localFilters.price.min || !localFilters.price.max) {
      setLocalErrors((prevErrors) => ({
        ...prevErrors,
        price: true,
      }));

      return;
    }

    if (Number(localFilters.price.min) > Number(localFilters.price.max)) {
      setLocalErrors((prevErrors) => ({
        ...prevErrors,
        price: true,
      }));

      return;
    }

    // If everything is okay, submit the form
    setFilters(localFilters);
    localStorage.setItem('filters', JSON.stringify(localFilters));
  };

  

  const handlePriceChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;

    setLocalFilters((prevState) => {
      const updatedPrice = {
        ...prevState.price,
        [name]: value,
      };

      const minPrice = Number(updatedPrice.min);
      const maxPrice = Number(updatedPrice.max);

      const hasError = minPrice >= maxPrice;
      setLocalErrors((prevErrors) => ({
        ...prevErrors,
        price: hasError,
      }));

      return {
        ...prevState,
        price: updatedPrice,
      };
    });
  };

so what i am interested in is NewDropdown component when handleSubmit happends the error should stop the function from compleating but for some reason the previous value of state is passed to it.

// dropdown component where error is suppose to decide if it closes it
import { useEffect, useRef, useState } from 'react';
import upIcon from '../../assets/images/DropdownIconUp.svg';
import downIcon from '../../assets/images/DropdownIconDown.svg';
import Button from '../button/Button';

type Props = {
  children: React.ReactNode;
  buttonText: string;
  dropdownTitle: string;
  onSubmit: () => void;
  error?: boolean;
};

const NewDropdown = ({
  children,
  dropdownTitle,
  buttonText,
  onSubmit,
  error = false,
}: Props) => {
  const [isOpen, setIsOpen] = useState(false);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  /* content outside of dropdown will trigger setIsOpen(false) */
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        buttonRef.current &&
        !buttonRef.current.contains(event.target as Node) &&
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const handleClick = () => {
    setIsOpen((prevState) => !prevState);
  };

  const handleSubmit = () => {
    console.log('err', error);
    onSubmit();
    if (!error) {
      setIsOpen(false);
    }
  };

  return (
    <div className='relative'>
      <button
        ref={buttonRef}
        onClick={handleClick}
        className={`rounded-md py-2 px-[14px] flex justify-center items-center gap-1 text-text font-medium ${
          isOpen ? 'bg-selected' : 'bg-transparent'
        }`}
      >
        {buttonText}
        <span>
          <img
            src={isOpen ? upIcon : downIcon}
            alt={isOpen ? 'menu open icon' : 'menu closed icon'}
          />
        </span>
      </button>
      {isOpen && (
        <div
          ref={dropdownRef}
          className='absolute bottom-0 transform translate-y-full left-0 p-6 rounded-[10px] border border-border bg-white z-20'
        >
          <p className='font-firago font-medium mb-6'>{dropdownTitle}</p>
          {children}
          <div className='flex justify-end mt-[32px]'>
            <Button
              className='bg-primary text-white py-2 px-[14px] rounded-lg font-firago font-medium transition-colors duration-200 ease-linear hover:bg-primaryHover'
              onClick={handleSubmit}
            >
              არჩევა
            </Button>
          </div>
        </div>
      )}
    </div>
  );
};

export default NewDropdown;

My guess was that the state was old so I used let variable instead but with that the error does not update at all because it is not a react state

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