skip to Main Content

I have to useState declarations:

const [selectedFromYear, setSelectedFromYear] = useState(1900);

const [toYearOptions, setToYearOptions] = useState([])

My component is populating the array years to bind in select options, great, but upon someone selecting say 2015 and this setting selectedtedFromYear I need to repopulate the available toYearOptions to remove any prior to 2015.

I have useEffect listening to selectedFromYear but how do I access/change toYearOptions inside this useEffect?

2

Answers


  1. If what you are doing is just computing options based onselectedFromYear only, then its better to use useMemo instead of state.

    
    const toYearOptions = useMemo(() => {
      // Write your logic to get Array
      return [...Array(10)].map((v, i) => selectedFromYear + i);
    }, [selectedFromYear]);
    
    
    Login or Signup to reply.
  2. You can access and update the toYearOptions state variable inside the useEffect by simply calling the setToYearOptions function.

     const [selectedFromYear, setSelectedFromYear] = useState(1900);
     const [toYearOptions, setToYearOptions] = useState([]);
    
     useEffect(() => {
    // Filter the options to remove years before selectedFromYear
    const filteredOptions = toYearOptions.filter(year => year >= 
    selectedFromYear);
    
    // Update the toYearOptions state with the filtered options
    setToYearOptions(filteredOptions);
    }, [selectedFromYear]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search