简体   繁体   中英

useEffect is not updating the default value of react-hook-form when creating edit form

I´m trying to populate the values of material-ui datepicker fields when rendering the edit form component, I can see in the console that the date object is being created correctly, but its not passing to the state, dont know what i´m doing wrong.

Here is the component


function DatePickerField(props) {

    const { field , studentValues, control} = props;
    const classes = useStyle();
    const [date, setDate] = useState(null);
   
    
    const handleChange = (date) => {
        setDate(date)
               
    }

    

    // Check if the input name of the field we get from knack match the input name of the form and if yes display the value
    useEffect(() => {
        if (studentValues) {
            const dataStudentArranged = DataStudent(studentValues);
            dataStudentArranged.forEach((card) => {
                card.cardValues.forEach((cardValue) => {
                    
                    if (cardValue.formName === field.formName) {
                        const dateObject = fromUnixTime(cardValue.value/1000)
                        setDate(dateObject)
                        console.log('date object =>',dateObject)
                    }
                })
            })
        }
    }, []);

    return (
        <TableRow>
            <TableCell>
                <Controller defaultValue={date} name={field.formName} control = {control}
                as = {
                <DatePicker 
                    className={classes.datePicker}
                    inputVariant = "outlined"
                    label={field.label}
                    value={date} 
                    onChange={handleChange}
                    autoOk
                    variant="inline"
                    format= "dd, MMMM yyyy"
                    size="small"
                    />
                } 
                />
            </TableCell>
        </TableRow>
    )
}

export default DatePickerField


Thanks!

The problem was with the react-hook-form, it was always passing the default values even after using useEfect, this question helped me to solve the issue: https://stackoverflow.com/a/62243132/9813493

Basicly when using react-hook-form with the control prop we should use the setValue function https://react-hook-form.com/api#setValue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM