I am using web components, the component has a .selectItem() method, and I am hitting it from the ref from useRef. The problem I am running into is that I can’t use that method later in my code unless I try and run it once.
useEffect(() => {
if (countrySelectorRef.current && departmentSelectorRef.current) {
countrySelectorRef.current.selectItems = countries;
countrySelectorRef.current.selectItem();
countrySelectorRef.current.addEventListener(
'eds-single-select__item-selected',
(e: CustomEvent) => {
setCountry(e.detail);
//Reset second dropdown on country select
setDepartment('');
departmentSelectorRef.current.selectItem();
},
);
departmentSelectorRef.current.selectItems = departments;
departmentSelectorRef.current.addEventListener(
'eds-single-select__item-selected',
(e: CustomEvent) => {
setDepartment(e.detail);
},
);
}
}, []);
Without
countrySelectorRef.current.selectItem();
my later function to pull the data from query params and pre select the item wont work
useEffect(() => {
if (
countrySelectorRef.current &&
departmentSelectorRef.current &&
searchParams
) {
countrySelectorRef.current.selectItem(searchParams.get('country'));
departmentSelectorRef.current.selectItem(searchParams.get('department'));
}
}, []);
There has to be something I am missing in the rendering lifecycle as to why calling it fixes it to be used later one but without it on the ref it doesn’t work?