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?