I have created a popup that the user can use to add stuff to the application, every field is a separate component, because I need to reuse them in several places in different configruations.
I have tried to create an innerRef that when changed (i.e. new value is typed), the useEffect of the component should be triggered to show or hide the Done button if all values are valid.
I know that all values are valid or not from the valid prop that I assign to .current
export default function AddStock() { const selectTypeOfQuantityRef = useRef({}); const [allValid, setAllValid] = useState(false); useEffect(() => { const allValues = [selectTypeOfQuantityRef.current.valid]; allValues.every((value) => value) ? setAllValid(true) : setAllValid(false); console.log(allValues.every((value) => value)); // does not get triggered }, [selectTypeOfQuantityRef.current]); return ( <> <AddPopup> <SelectTypeOfQuantity innerRef={selectTypeOfQuantityRef} /> {allValid && <DoneButton/>} <CancelButton/> </AddPopup> </> ); } And this is the select itself (custom of course), that sets innerRef, whenever its state changes. Everything here works, the state of this small component itself is managed correctly, but it just does not get triggered the state update of the parent component
export default function SelectTypeOfQuantity({ defaultValue = null, innerRef }) { const [selectTypeOfQuantity, setSelectTypeOfQuantity] = useState(defaultValue); const [valid, setValid] = useState(false); const [errMessage, setErrMessage] = useState("Избери стойност!"); useEffect(() => { innerRef.current.value = selectTypeOfQuantity; handleValidation(selectTypeOfQuantity); }, [selectTypeOfQuantity]); const handleValidation = (value) => { const result = validateAutocomplete(value); if (result.valid) { setValid(true); setErrMessage(null); innerRef.current.valid = result.valid; } else { setValid(false); setErrMessage(result.errMessage); } }; const selectTypeOfQuantityOnChange = (e, val) => { setSelectTypeOfQuantity(val ? val.value : null); }; return ( <Select onChange={selectTypeOfQuantityOnChange}/> ); }
SelectTypeOfQuantityOnChange. Its case sensitive issue i guess here in the first lookallValidcondition), its just that I cant show back theDoneButton