'How to persist selected value for Material UI Autocomplete on mount?
I made an Autocomplete component using react-hook-form and Material UI's autocomplete. The form is a wizard-form (multistep form) so when I switch steps the component unmounts. Here's the code
import { useState, useEffect } from "react";
import { Autocomplete as MuiAutcomplete} from "@mui/material";
import {useFormContext} from "react-hook-form";
interface props {
name: string,
options?: string[],
getOptions?: (value: string) => { // For fetching values while typing
label: string,
id: number
}[],
};
const Autocomplete = ({name, options=[], getOptions}: props) => {
const [autcompleteValues, setAutocompleteValues] = useState<any[]>([]);
const {watch, register} = useFormContext();
const watchValue = watch(name);
useEffect(() => {
if (getOptions) {
setAutocompleteValues(getOptions(watchValue));
}
}, [watchValue]);
return (
<MuiAutcomplete
options={getOptions? autcompleteValues: options}
renderInput={({InputProps, inputProps}) => (
<div ref={InputProps.ref}>
<input type="text" {...inputProps} className="bg-transparent outline-none p-1"/>
</div>
)
}
getOptionLabel={option => option.label || option}
{...register(name)}
/>
)
}
export default Autocomplete
The component works just fine but when I switch steps and go back to it, the input field is empty. The value is still registered but it doesn't show in the input box. How can I make it so the value gets saved even if I switch pages?
Solution 1:[1]
I am not sure if you figured it out but make the following changes on your Autocomplete component like this:
const { watch, register, setValue, getValues } = useFormContext();
get the getValues and setValue function from useFormContext
Have them placed like this in Mui control (remove register altogether):
<MuiAutcomplete
options={getOptions ? autcompleteValues : options}
renderInput={({ InputProps, inputProps }) => (
<div ref={InputProps.ref}>
<input
type="text"
{...inputProps}
className="bg-transparent outline-none p-1"
/>
</div>
)}
value={getValues(name)}
onChange={(e, v) => {
console.log("Mui change", v);
setValue(name, v);
}}
getOptionLabel={(option) => option.label || option}
/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mujeeb Qureshi |
