Функция useForm() не обновляется после извлечения данных с помощью функции useEffect() — Next.js

#reactjs #next.js #use-effect #use-state #use-form

Вопрос:

Форма не обновляется после извлечения данных из базы данных с помощью useEffect.

Эффект использования

 useEffect(() => {
    async function fetchData() {

      const res = await fetch(process.env.NEXT_PUBLIC_API   `/resume/${user?.sub?.split('|')[1]}`);
      const data = await res.json();

      updateResume(data?.resume || {});
    }
    fetchData();
  }, []);
 

Использовать

 const [storedResume, updateResume] = useState({} as any);
 

Форма использования

 const { register, handleSubmit, watch, formState: { errors } } = useForm<any>({
    resolver: yupResolver(schema),
    defaultValues: storedResume || {},
  });
 

Я также попытался изменить storedResume на переменную и useRef тоже. Не работает.

Кроме того, я могу видеть данные в console.log()

Я не могу использовать getStaticProps из Next.js так как мне нужен идентификатор пользователя для передачи URL-адреса выборки.

Полный Исходный Код 🔗

Данные из БД

 {"_id":"6167140a042e6430dd849603","user":"104494318779322042776","resume":{"personal":{"firstName":"Aravind","lastName":"Appadurai","email":"aravin.it@gmail.com","phone":"9710549943","summary":"To gain a dynamic and challenging role in Information Technology, that will offer me the best opportunity for the further development of abilities, skills, and knowledge in a well-established firm with long term career growth possibilities."},"education":[{"institution":"Bhajarang Engg College","subject":"B. Tech (Information Technology)","startDate":"2010-04","endDate":"2014-04","score":7.5,"location":"Chennai","index":0},{"institution":"Salvation Matriculation School","subject":"HSC (12th)","startDate":"2009-04","endDate":"2010-04","score":6.5,"location":"","index":1}],"employment":[{"title":"Senior Software Engineer II","company":"Everi Fintech","startDate":"2018-08","endDate":"","location":"Chennai","isCurrent":true,"summary":"Leading and Co-ordinating the team and completing the project/features/work item on the time. Supporting the peer for their queries and issues. Attending the meeting with management and consolidating the requirements. Supporting for Production issues.","index":0},{"title":"Senior Engineer","company":"CSS Corp","startDate":"2017-02","endDate":"2021-07","location":"Chennai","isCurrent":false,"summary":"Maintaining and Feature enhancement for existing web application using ASP.NET MVC, C#, Oracle Databases, Web/Windows Service, ADS server and Angular.n","index":1}],"skills":[{"name":"Node.js","level":3,"index":0},{"name":"JavaScript","level":3,"index":1},{"name":"TypeScript","level":3,"index":2},{"name":"React.js","level":2,"index":3},{"name":"Next.js","level":3,"index":4},{"name":"Express.js","level":4,"index":5},{"name":"Angular.js","level":2,"index":6}],"language":[{"name":"Tamil","level":3,"index":0},{"name":"English","level":3,"index":1}],"links":[{"label":"Blog","link":"https://www.aravin.net","index":0},{"label":"GitHub","link":"https://www.github.com/aravin","index":1}],"course":[{"name":"70-483 - Programming in C# (MCP)","institution":"Microsoft","startDate":"","endDate":"","email":"friend@google.com","phone":"9710549943","index":0}],"reference":[{"name":"Friend Name","company":"Google","email":"aravin.it@gmail.com","phone":"9710549943","index":0}]}}
 

Комментарии:

1. Форма, похоже, на самом деле не использует storedResume, так зачем же ее обновлять? Ни одно из состояний формы не изменилось.

2. Я установил значение по умолчанию. Я сделал комментарий.

Ответ №1:

После тщательного анализа исправлена эта проблема, вызвав сброс формы использования в useEffect

   useEffect(() => {
    setResume(data?.resume);
    reset(data.resume); --> FIX
  }, [reset, data.resume]);
 
 const { register, handleSubmit, watch, reset, formState: { errors } } = useForm<any>({
    resolver: yupResolver(schema),
    defaultValues: storedResume || {},
  });