react-hook-form's useFieldArray function does not display data from an API when values are passed in

Utilizing a fieldArray, I am constructing a form with react-hook-form. This form serves the dual purpose of creating and updating a user, and makes use of the "values" prop from react-hook-form. The field within the fieldArray API consists of two basic time inputs, accompanied by an "add" button that generates additional time inputs (initially empty).

default form
added field

The issue arises when fetching data prior to initializing this form, whereby if there is any breakTime present in the array field, it fails to render promptly on the UI. However, upon clicking the add button, all fields retrieved from the API are rendered simultaneously. (refer to images below)

all fields filled, except the array field

after clicking on add button of array field

My code snippet:

const form = useForm<OperatorOrManageData>({
    resolver: zodResolver(operatorOrManagerSchema),
    defaultValues: initializeDefaultValues(),
    mode: "all",
    values: data,
})

const { fields, append, remove } = useFieldArray({
    name: "breakTime",
    control: form.control,
})

    {fields.map((field, index) => (
                                    <div className="...">
                                        ...
                                    </div>
                                ))}

I attempted implementing a controlled field array as outlined in the documentation https://react-hook-form.com/docs/usefieldarray, but was unsuccessful.

Answer №1

@Ja1za1, Greetings! To retrieve your data from the parent component and display a loading state until the data is fetched, you can follow this approach:

Parent Component Example:

const Parent = () => {
  const {data, isLoading} = fetch("url");

  if(isLoading) {return <Loading />}

  if(data) {
     return <Child data={data} />
   }
}

return null

Child Component Example:

//CHILD
const Child = ({data}) => {
  const form = useForm<OperatorOrManageData>({
    resolver: zodResolver(operatorOrManagerSchema),
    defaultValues: initializeDefaultValues(),
    mode: "all",
    values: data,
  })
   //...other codes
}

Note: Be cautious while using

form.watch("inputFieldName")
as it may result in an array of fields with undefined values if disabled property is used.

For example: cars:[{value: undefined].

Make sure to employ readOnly attribute with the Input component rather than the FormField.

Incorrect Usage:

<FormField disabled control={form.control} name={` urls.${index}.value`} .....    />

Incorrect Usage:

<Input disabled placeholder="type here" />

Correct Usage:

<Input readOnly placeholder="type here" />

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

Utilizing innerHTML of the <select> tag with windows.open()

I am working on a feature for my website where users can select one option from a dropdown menu and when they click on the button labeled "connect", it should open a new tab with the corresponding link. Here is the code I have so far: <select name="ch ...

Transforming unprocessed string information with a set position-dependent format into a structured format such as JSON

Here is the scenario I am dealing with: The input format consists of a string with a fixed total length, where each set of fixed positions represents a different value. For example, if the input is "ABCDE12345", position 1 to 3 ("ABC" ...

Uncovering Modified Form Elements Using jQuery

I am managing a form with the ID "search_options" and tracking changes in the form using the following code: $("#search_options").change(function() { // Bla Bla Bla }); Within this form, I have various inputs including one with the ID "p ...

Error 19: Constraint violation - duplicate entry detected

While trying to set up my app, create a local database, and insert the very first user who has logged in locally, I encountered an error message at a specific point in the code. Here's where it happened: angular.module("greenApp") .service("d ...

Content is deleted by ng-bind-html following the < symbol (less than sign)

In my current project using angular v1.5.6, I have html data entered by users with special characters which are stored in the database. For example: var txt = "<span class='txt_bold'> content with <lessthan signs<span> <span> ...

Jquery unresponsive in AJAX form output presentation

I recently delved into the world of jquery and AJAX, and while I grasp most concepts, I'm struggling with a small code snippet. On my webpage, there is a summary of articles. Clicking on an article name triggers a popup window with detailed informati ...

In my specific scenario, what is the most effective method for retrieving data from an EntityFramework database using JavaScript?

Currently, within my ASP.NET MVC Core2 project, I have a model in the EF database that contains multiple properties: public class SchoolEvents { public long ID { get; set; } [Required] [StringLength(40, ErrorMessage = "Max 40 c ...

Is there a way to establish the position of a mesh in three.js before integrating it into the scene?

How can I add a mesh to a specific position in the scene using three.js? I attempted the following code without success: // mesh refers to an instance of THREE.Mesh // scene is an instance of THREE.Scene scene.add(mesh) scene.updateMatrixWorld(true) mesh. ...

Ways to stop two JavaScript files from running at the same time

After combining two JavaScript files, I am facing some issues. The first file handles validation while the second one has an ajax plugin for form submission after validation. When I include these files in the header section, they both run simultaneously. H ...

Can someone help clear up this confusion with CSS?

Why is image 6.png selected, when all the images are direct descendants of the div shape? Thank you for your assistance, it's greatly appreciated. As far as I know, it should select all the divs because they are all direct descendants of the div #shap ...

Display a popup in Angular 4 when a click event is triggered by a separate

I am currently facing an issue that I can't seem to solve. My objective is to display a popup div on the page when clicking on a menu entry in my navbar.component. In order to achieve this, I introduced a property called "show" in my popup component ...

Substitute placeholders in the HTML code with Angular syntax

Lately, I have been encountering some issues with AngularJS. I have defined multiple scopes like this: app.controller('mainController', function($scope) { $scope.siteURL = "my website url"; }); When using the {{siteURL}} variable in ...

In my chat application, I encountered the error message "Received an expression instead of an assignment or function call - no-unused-expressions"

While working on my React Chat app and trying to access my Firebase, I encountered the error message: "Expected an assignment or function call and instead saw an expression no-unused-expressions" The error seems to be related to the assignment of this.rem ...

What could be the reason behind the button's lack of color change with this particular code?

I'm a beginner in web development and currently practicing HTML, CSS, and Javascript. I've added a button to my html file and would like the color of the button to change when it's clicked on. Here is my HTML code: <button id="box&q ...

What is the best way to keep a text editable in a razor editor without it vanishing?

I'm on a quest to find the name for a certain functionality that has been eluding me, and it's truly driving me up the wall. Check out the razor code snippet I've been using to exhibit my form inputs: <div class="col-sm"> ...

What is the best approach to creating customizable modules in Angular2?

I'm exploring the most effective approach to configuring modules in Angular 2. In Angular 1, this was typically achieved through providers. As providers have been altered significantly, what is the preferred method for passing configuration parameters ...

I could use some assistance with deciphering JSON data

After using console.log to display the data I received, I observed an object structured as follows (I trimmed some details for clarity and used ... to indicate repetitive information): [ Submission { title: 'Untitled', content: { ur ...

The specified width and height for a div containing images are not being accepted by Firefox

I am facing an issue with the CSS for a div that contains images and is not displaying any width: .wide{ width:5000px; height:100%; overflow: hidden; z-index: 1; display:none; } Here is the HTML code for the div: <div class="wide ...

The issue persists with the MVC Controller parameter returning as null consistently, especially when the object field is

When using JavaScript to call a controller and process a function, I encountered an issue where the parameter value (name in summary) is null when the field is set to private. However, the function works correctly when the field is set to public. Is settin ...

How come my website is loading a JavaScript file with outdated content?

After making edits to a JavaScript file that replaces specific HTML tags with new language translations, I noticed that the changes were not reflected correctly on the website. Even after clearing my history and cache, Firebug still showed the old content ...