0
export default function CitySearch() {
  const defaultCity = "London";
  const [city, setCity] = useState(defaultCity);
  const address = useSelector((state) => state?.cityDetails?.city);
  const classes = useStyles();

  const handleOnChange = (e) => {
    setCity(e.target.value);
  };
  const handleOnBlur = () => {
    if (city) setCity(city);
    else if (address) setCity(address);
    else setCity(defaultCity);
  };

  useEffect(() => {
    setCity((prevState) => address);
  }, [address]);
  return (
    <Box className={classes.root}>
      <TextField
        label="City"
        variant="outlined"
        value={city}
        onChange={handleOnChange}
        onBlur={handleOnBlur}
      />
    </Box>
  );
}

The code works fine but throwing this error on console "Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component."

But the error goes off when i comment out the code inside useEffect

1 Answers1

1

Try to check the value of address by console.log(address). If the value of address is null or undefined then this error will come.

Try this

useEffect(() => {
    setCity((prevState) => address??'');
  }, [address]);

This will set the state as empty string if the value of address is undefined or null.

Another alternative is to avoid setCity if address is undefined or null i.e.

useEffect(() => {
if(address) setCity((prevState) => address);
  }, [address]);
Zohaib
  • 119
  • 4