When using React hooks forms, setting default values from a reduced array does not automatically populate the form. However, manually entering the same object into the form does

As I work with react hooks forms, I am facing a challenge in setting default values for a form generated by mapping over an array to output the inputs. After reducing the array into an object format like {name0:"fijs",name1:"3838"...}, manually passing this object as default values successfully populates the form inputs. However, when attempting to do this from the variable used in the reduce function, it fails to populate. I suspect this is due to it being undefined on the initial render. Even after trying to implement a useEffect hook, the issue remains unresolved.

The section of code causing trouble:

const test = formState?.reduce((obj, item, idx) => {
    return { ...obj, [`${item.name}${idx}`]: "fdsjfs" };
  }, {});

  const { register, handleSubmit, errors } = useForm({
    defaultValues: test,
  });

  console.log(test);

Below is the complete code snippet:

import { useQuery, gql, useMutation } from "@apollo/client";
import { useEffect, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import { useForm } from "react-hook-form";

// Rest of the code...

UPDATE: Despite trying to use useEffect with a reset method from the api, the issue persists.

const { register, handleSubmit, errors, reset } = useForm();

useEffect(() => {
    const result = test;
    reset(result);
  }, [reset]);

UPDATE: In an attempt to resolve the issue, I encapsulated the Form component separately but unfortunately, the problem still lingers.

Form.js

// Code snippet for Form component

index.js

// Remaining code logic in index file importing and utilizing the Form component

Answer №1

To optimize the code, consider separating the form into its own component and rendering it only after fetching the data. This approach ensures that when using useForm in the child component, the default values will be correctly set.

const Home = () => {
  const { loading, error, data } = useQuery(INPUT_VALUES)
  const blankFormInput = {
    __typename: "FormInputVal",
    name: "test",
    _id: uuidv4(),
    type: "text",
  }
  const [formState, setFormState] = useState([blankFormInput])

  // other code

  if (loading) {
    return <p>Loading...</p>
  }

  return <MyForm defaultValues={formState} />
}

If you prefer to keep the current structure, you can set the input values using setValue once the data is fetched.

useEffect(() => {
  const formData = data?.allFormInputVals?.data
  setFormState(formData)

  formData?.forEach((item, idx) => {
    setValue(`${item.name}${idx}`, 'whatever')
  })
}, [data])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to locate request object during post request

I've created a pug form with the following structure: extends layout block content h1 David A Hines h2 #{posts[0].title} p #{posts[0].body} div form(action='/insert_post',method='post') div(id='title_div' ...

Alter the icon of the scroll button on the Material UI Tabs element

How can I change the icons for the scroll buttons (left and right) on my Tabs component? I see that there is a prop called 'ScrollButtonComponent', but I am unsure how to use it to assign different icons to the left and right buttons. Here is a ...

Interactive table created with DataTables that automatically updates the dynamic JSON data source whenever changes are made to the table

Using the Datatables plugin, I am dynamically populating a table with HTML rendered from a JSON array. However, I need the table to update the model (datasource) stored client-side whenever an edit is made. When navigating to a new page on the table, it s ...

Determine the minimum and maximum width of jQuery UI resizable during the "resizestart" event

As a newcomer to Javascript, I am facing challenges navigating my way around. Currently, I am attempting to create a jQuery plugin that will facilitate resizing elements using the jQuery UI resizable plugin. My goal is to implement logic that dynamically ...

SwitchBase is undergoing a transformation where its unchecked state goes from uncontrolled to controlled. It is important to note that elements should not transition back and forth between un

There is a MUI checkbox I am using: <Checkbox checked={rowValues[row.id]} onChange={() => { const temp = { ...rowValues, [row.id]: !rowValues[row.id] }; setRowValues(temp); }} in ...

Set up an array data by extracting values from an array prop within a Vue component

Within my Vue component, I am dealing with an array prop called selectedSuppliers that consists of objects. My goal is to set up a data property named suppliers and initialize it with the values from selectedSuppliers. However, I do not want any modificati ...

Extracting JavaScript variable data to PHP using Ajax technology

I've been trying to save latitude and longitude values in PHP variables, but I'm having trouble. Here is the code I'm using. Can anyone please help me figure out why these values are not being stored in PHP variables: Code: <!DOCTYPE h ...

Update Jquery Dialog's Button After Making an Ajax Request

I am facing an issue with my dialog window that contains some confirmation elements following a form submission: $('#newUserDialog').dialog({ autoOpen: false, width: 600, modal: true, resizable: false, cl ...

Issue with Vue.js where the v-if directive placed inside a v-for loop does not properly update when

I want to dynamically show elements from an array based on boolean values. However, I am facing an issue where the element does not disappear even after the boolean value changes. <li v-for="(value, index) in list"> <span> {{ value[0] }} & ...

Implementing Material UI styles within a React component

Discover a unique way of incorporating Material UI styles outside of a React component. import React from 'react'; import { makeStyles } from '@material-ui/styles'; import Button from '@material-ui/core/Button'; const useSty ...

Using EJS to Render a Function Expression?

Has anyone been able to successfully render a function call in express using EJS? Here's what I've tried so far: res.render("page", { test: test() }); Can someone confirm if this is possible, or provide guidance on how to call a function fr ...

Navigate to the same destination with React Router Dom while passing state as a parameter

Let's talk about a scenario with a Link setup like this: <Link to={`/samelocation/${id}`} state={{ state1: 'hello' }}> This link is nested in a sub-component within the main component situated at /samelocation/:id. To ensure that the ...

Encountering an async issue with npm exiftool in JavaScript

I'm facing issues with npm exiftool usage. (https://www.npmjs.com/package/exiftool) I'm attempting to perform some tasks using it. Iterate through image files in a specific folder Retrieve 'xpKeywords' data of each image file Write th ...

trigger an onChange event when initializing the value

I'm currently working on creating a select field that will automatically choose an Entry when there's only one option available. The issue I'm facing is that the onChange event isn't triggered when setting the value in the list. Is ther ...

Stop Swiper Slide from moving when clicked on

I am currently utilizing Swiper JS and have encountered an issue. In my Swiper slider, each slide contains a button. Whenever I click on the slide or the button itself, the slide becomes the active one, causing the entire slider to move. Is there a way to ...

Issue with hasClass and addClass not working as expected

Why isn't the script below adding a class (.active) to .global-header when .navigation.primary has a class of .active? JS if($(".navigation.primary").hasClass("active")) { $('.global-header').addClass('active'); } HTML < ...

'An error occurred when invoking the class method due to 'This' being undefined

I'm attempting to display a response message to the user, but encountering an error (Cannot read property 'message' of undefined). Here's the code snippet causing the issue: server.js const server = express(); let App = require(' ...

Issue with Typescript and react-create-app integration using Express

I'm relatively new to Typescript and I decided to kickstart a project using create-react-app. However, I encountered an issue while trying to connect my project to a server using express. After creating a folder named src/server/server.ts, React auto ...

Implementing the insertion of a <div> element within an input field using jQuery

<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></scr ...

How can I use PHP and JavaScript to iterate through a <select> / <option> list and gather the values?

I am working on a project where I have a group of options within a selection dropdown and my goal is to utilize JavaScript to deselect all chosen values, gather them into a string, and then send it over to my PHP script. ...