0

In my react 18.2.0 I have the following structure for my code

   const [searchParams, setSearchParams] = useState({
      shoes:false,
      hoodies:false
   });

  const handleShoesDropDownChange = (e, v, setSearchParams) => {
    console.log(' value ' ,  v); // I can see the log OK
    console.log(' search params ' ,  searchParams); // i can see previous state OK
    //the following works, it changes the search paramns
    //but the autocomplete doesnt update the selected value
    setSearchParams(prevState => ({
      ...prevState,
      shoes: v.id
    }))
  }  

    useEffect(() => {
    //...
    }, []);



 return (
    <div className='generalcontainer'  >   

<Drawer>

  <Box>

            <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
              <Tabs value={valueSearchTab} onChange={handleChangeSearchTab} aria-label="tabs" scrollButtons>
                <Tab label="Shoes" {...a11yProps(0)} />
                <Tab label="Hoodies" {...a11yProps(1)} /> 
              </Tabs>
            </Box>

            <TabPanel value={valueSearchTab} index={0}>

              {
                searchCategoriesInfoSelector.success!==true?
                <Box >Loading search components</Box>
                :
                searchCategoriesInfoSelector.data.shoes&& searchCategoriesInfoSelector.data.shoes.length>0? 

                <Box>   

                  <Autocomplete
                    id="combo-box-shoes"
                    options={searchCategoriesInfoSelector.data.shoes}
                    onChange={(event, value)=>handleShoesDropDownChange(event, value, setSearchParams)}
                    renderInput={(params) => <TextField {...params} label="Select shoes" />}
                  />    

                  <Button  
                    onClick={()=>searchByShoes(searchParams)}
                  >
                    Go                    
                  </Button >
                  
                </Box>  
                :
                'loading search bar'
              }

            </TabPanel>  


  </Box>

</Drawer>

there is a state, an autocomplete and a function that is called when autocomplete changes, to alter the state The autocomplete is inside a Tab.

When autocomplete changes the onChange function is called successfully and alters the state successfully. The issue is that the autocomplete doesnt change its value to the selected one. If I remove the part that alters the state, autocomplete changes its value to the selected.

How can I fix this?

slevin
  • 4,166
  • 20
  • 69
  • 129

1 Answers1

0

As soon as you use one of the props value/onChange, your component become "Controlled".

It means you have to provide both onChange and value props. onChange handle the event, value will contain the current value. Use a state variable to store the current value and give it to your component.

See more on MUI documentation : Controlled autocomplete

Guillaume
  • 319
  • 1
  • 11