many-yun
many-yun

Reputation: 21

child component pass props to parent's useState -> returning undefined (react)

I want to put the props from the child component into the value of useState from the parent component, but it also comes with undefined. How can I not get undefined?

Child component

const FilterSelect = props => {
  const [filterUser, setFilterUser] = useState('all')

  const handleFilterUser = ({ target }) => {
    setFilterUser(target.value)
  }
  useEffect(() => {
    props.propFunction(filterUser)
  }, [filterUser])

  return (
    <Box sx={{ width: 120 }}>
      <FormControl fullWidth>
        <Select
          size="small"
          labelId="user-select-label"
          id="user-select"
          value={filterUser}
          label="filter"
          onChange={handleFilterUser}
        >
        </Select>
      </FormControl>
    </Box>
  )
}

parent component

import FilterSelect from './components/FilterSelect'

const UserList = () => {
  const [filterSelectOne, setFilterSelectOne] = useState('all')

  const highFunction = text => {
    setFilterSelectOne(text)
  }

  useEffect(() => {
    highFunction()
  }, [])

  console.log(filterSelectOne) // 'all', undefined

  return (
    <Box sx={{ width: '100%' }}>
      <Paper sx={{ width: '100%', mb: 2 }}>
        <FilterSelect propFunction={highFunction} />
      </Paper>
    </Box>
  )
}

enter image description here

Upvotes: 1

Views: 41

Answers (1)

diedu
diedu

Reputation: 20825

Remove the use effect where you call the highFunction with no parameters in the parent component

Upvotes: 1

Related Questions