bug: Select component is not controllable

1
open
YashKandalkar
YashKandalkar
Posted 5 months ago

bug: Select component is not controllable #607

Bug report 🐞

Version & Environment

  • Version of browser - Google Chrome 92.0.4515.131 (Official Build) (64-bit)
  • Version of geist-ui/react - 2.2.0

Expected Behaviour

The Select component should give priority to the value prop, if the value prop is given then only select the item(s) in the value prop, making the component controllable.

Actual results (or Errors)

Currently, even after giving the value prop, the component still changes it's value, even if the state hasn't changed.

A codesandbox explaining the bug

unix
unix
Created 5 months ago

You need to set the state to an explicit dependency to ensure that changes can be tracked:

useEffect(() => {
    setInterval(() => {
      setSelected(selected === 'public' ? 'private' : 'public')
    }, 4000)
  }, [selected])

Or, you can use no external dependencies:

useEffect(() => {
    setInterval(() => {
      setSelected((val) => (val === 'public' ? 'private' : 'public'))
    }, 4000)
  }, [])

After my test, both solutions are finished working properly. However, if you depend on state only in FC components, state is not the value you see, the reason setInterval doesn't work is that the selected value it depends on doesn't change. This blog (a-complete-guide-to-useeffect) may help you understand this issue