Dependent select boxes in form

I'm using TanStack Query to fetch a configuration from an API. Once fetched, I'd like to populate two select boxes with the first available configuration in the response. options is an alias for the data returned by useQuery. Both vehicle_type and validity are initially set to "" (empty string). form comes from useForm (React Hook Form).
useEffect(() => {
const vehicleType = form.getValues("vehicle_type");
if (options && !vehicleType) {
const firstVehicleType = options.vehicle_types[0];
const firstValidity = firstVehicleType.validities[0];
form.setValue("vehicle_type", firstVehicleType.type);
form.setValue("validity", firstValidity);
}
}, [options, form]);
useEffect(() => {
const vehicleType = form.getValues("vehicle_type");
if (options && !vehicleType) {
const firstVehicleType = options.vehicle_types[0];
const firstValidity = firstVehicleType.validities[0];
form.setValue("vehicle_type", firstVehicleType.type);
form.setValue("validity", firstValidity);
}
}, [options, form]);
vehicle_type gets set correctly, but validity doesn't, or at least the value isn't rendered / changing its value does not trigger a re-render? There must be some fundamental thing I don't get here.
1 Reply
Rivenris
Rivenris7d ago
How does the value change in the options object? Does the reference to options/data update when your values inside change from within the code?

Did you find this page helpful?