Here is my code ... I want to set default value of a input field by react-hook-form but its showing me the variable(problemName) value "undefine" ... I am checking its value in console.log(problemName) ...its showing my expected value
import axios from 'axios';
import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { useNavigate, useParams } from 'react-router-dom';
const SingleProble = () => {
const navigate = useNavigate();
const { problemNames } = useParams();
const [data, setData] = useState([]);
useEffect(() => {
axios.get(`http://localhost:5000/problems/math/${problemNames}`)
.then(res => {
setData(res.data)
})
}, [problemNames])
const { problemName, score, problemDetails, level, problemAns, tried, solved, failed } = data
const defaultValues = {name:problemName}
const { register, handleSubmit } = useForm({ defaultValues })
CodePudding user response:
this is because you have your useForm
initialized with {name: undefined}
as the data
is async. What you can do is either: 1) wrap the Form in a parent which fetches data and then passes data as a prop (or sets data in a Provider). or, 2) if you want to keep everything in 1 component you can re-write as:
const SingleProble = () => {
const { problemNames } = useParams();
const [data, setData] = useState([]);
const defaultValues = {name:problemName}
const { setValue } = useForm({ defaultValues })
useEffect(() => {
axios.get(`http://localhost:5000/problems/math/${problemNames}`)
.then(res => {
setData(res.data)
setValue('name', res.data.problemName)
})
}, [problemNames])
CodePudding user response:
You can take a look at this stackoverflow answer. Answer explains how it works.
https://stackoverflow.com/a/70667544/15052600
And you can also take a look at the similar question itself.