How to set an usestate with an object from another usestate array? - arrays

I need to set an usestate hook with the option selected from a datalist among another usestate array.
Here is my code :
import { useEffect, useState } from 'react';
export function ChooseCar() {
const [cars, setCars] = useState([]);
const [currentCar, setCurrentCar] = useState();
useEffect(() => {
declareCar();
}, [])
function declareCar() {
try {
setCars([]);
setCars(prev => [...prev, { _owner: "John", _brand: "Ferrari", _model: "F458" }]);
setCars(prev => [...prev, { _owner: "Jim", _brand: "Porsche", _model: "993" }]);
setCars(prev => [...prev, { _owner: "Joe", _brand: "Aston Martin", _model: "Vantage" }]);
console.log({ cars });
} catch (err) {
console.log(err);
}
}
function viewConsole() {
console.log(currentCar);
}
return (<div>
<label htmlFor="car-choice">Car :</label>
<input list="Car" id="car-choice" name="car-choice" onChange={e => setCurrentCar(e.target.value)} />
<datalist id="Car">
{cars.map(car => (
<option key={car._owner} value={car._owner}></option>
))}
</datalist>
<div>
<button onClick={declareCar}>Refresh</button>
<button onClick={viewConsole}>console</button>
</div>
<div>{currentCar}</div>
</div>)
}
I need to set my currentCar state with the selected car from the datalist. I'm able to set with car._owner or car._model, but not with the entire car object.
I hope I'm being explicit enough.
Thanks.
I tried to :
e => setCurrentCar(e.target.value)
with
value = car._owner
like in the example above. I tried to use :
<input list="Car" id="car-choice" name="car-choice" onChange={e => setCurrentCar(
e.target.owner,
e.target.brand,
e.target.model
)} />
<datalist id="Car">
{cars.map(car => (
<option key={car._owner} owner={car._owner} brand={car._brand} model={car._model} value={car._owner}></option>
))}
</datalist>
It resulted to currentCar = undefined.
I tried :
<label htmlFor="car-choice">Car :</label>
<input list="Car" id="car-choice" name="car-choice" onChange={e => setCurrentCar(e.target.value)} />
<datalist id="Car">
{cars.map(car => (
<option key={car._owner} value={car._owner} brand={car._brand} model={car}></option>
))}
</datalist>
But it resulted to [object Object]

Related

Two-way data binding on large forms

(After working through a React.js tutorial, I'm currently coding my first little app to get more practice. So this will be a newbie question and the answer is certainly out there somewhere, but apparently I don't know what to search for.)
Google lists a lot of examples on how to achieve two-way data binding for one input field. But what about large, complex forms, possibly with the option of adding more dynamically?
Let's say my form consists of horizontal lines of input fields. All lines are the same: First name, last name, date of birth and so on. At the bottom of the table, there is a button to insert a new such line. All this data is stored in an array. How do I bind each input field to its respective array element, so that the array gets updated when the user edits a value?
Working example with two lines of two columns each:
import { useState} from 'react';
function App() {
var [name1, setName1] = useState('Alice');
var [score1, setScore1] = useState('100');
var [name2, setName2] = useState('Bob');
var [score2, setScore2] = useState('200');
function changeNameHandler1 (e) {
console.log(e)
setName1(e.target.value)
}
function changeScoreHandler1 (e) {
setScore1(e.target.value)
}
function changeNameHandler2 (e) {
setName2(e.target.value)
}
function changeScoreHandler2 (e) {
setScore2(e.target.value)
}
return (
<div>
<table>
<tbody>
<tr>
<td><input name="name1" id="id1" type="text" value={name1} onChange={changeNameHandler1} /></td>
<td><input name="score1" type="text" value={score1} onChange={changeScoreHandler1} /></td>
</tr>
<tr>
<td><input name="name2" type="text" value={name2} onChange={changeNameHandler2} /></td>
<td><input name="score2" type="text" value={score2} onChange={changeScoreHandler2} /></td>
</tr>
</tbody>
</table>
{name1} has a score of {score1}<br />
{name2} has a score of {score2}<br />
</div>
);
}
export default App;
How do I scale this up without having to add handler functions for hundreds of fields individually?
You can still store your fields in an object and then just add to the object when you want to add a field. Then map through the keys to display them.
Simple example:
import { useState } from 'react'
const App = () => {
const [fields, setFields ] = useState({
field_0: ''
})
const handleChange = (e) => {
setFields({
...fields,
[e.target.name]: e.target.value
})
}
const addField = () => setFields({
...fields,
['field_' + Object.keys(fields).length]: ''
})
const removeField = (key) => {
delete fields[key]
setFields({...fields})
}
return (
<div>
{Object.keys(fields).map(key => (
<div>
<input onChange={handleChange} key={key} name={key} value={fields[key]} />
<button onClick={() => removeField(key)}>Remove Field</button>
</div>
))}
<button onClick={() => addField()}>Add Field</button>
<button onClick={() => console.log(fields)}>Log fields</button>
</div>
);
};
export default App;
Here is what I think you are trying to achieve in your question:
import { useState } from 'react'
const App = () => {
const [fieldIndex, setFieldIndex] = useState(1)
const [fields, setFields ] = useState({
group_0: {
name: '',
score: ''
}
})
const handleChange = (e, key) => {
setFields({
...fields,
[key]: {
...fields[key],
[e.target.name]: e.target.value
}
})
}
const addField = () => {
setFields({
...fields,
['group_' + fieldIndex]: {
name: '',
score: ''
}
})
setFieldIndex(i => i + 1)
}
const removeField = (key) => {
delete fields[key]
setFields({...fields})
}
return (
<div>
{Object.keys(fields).map((key, index) => (
<div key={key}>
<div>Group: {index}</div>
<label>Name:</label>
<input onChange={(e) => handleChange(e, key)} name='name' value={fields[key].name} />
<label>Score: </label>
<input onChange={(e) => handleChange(e, key)} name='score' value={fields[key].score} />
<button onClick={() => removeField(key)}>Remove Field Group</button>
</div>
))}
<button onClick={() => addField()}>Add Field</button>
<button onClick={() => console.log(fields)}>Log fields</button>
</div>
);
};
export default App;
You may want to keep the index for naming in which case you can use an array. Then you would just pass the index to do your input changing. Here is an example of using an array:
import { useState } from 'react'
const App = () => {
const [fields, setFields ] = useState([
{
name: '',
score: ''
}
])
const handleChange = (e, index) => {
fields[index][e.target.name] = e.target.value
setFields([...fields])
}
const addField = () => {
setFields([
...fields,
{
name: '',
score: ''
}
])
}
const removeField = (index) => {
fields.splice(index, 1)
setFields([...fields])
}
return (
<div>
{fields.map((field, index) => (
<div key={index}>
<div>Group: {index}</div>
<label>Name:</label>
<input onChange={(e) => handleChange(e, index)} name='name' value={field.name} />
<label>Score: </label>
<input onChange={(e) => handleChange(e, index)} name='score' value={field.score} />
<button onClick={() => removeField(index)}>Remove Field Group</button>
</div>
))}
<button onClick={() => addField()}>Add Field</button>
<button onClick={() => console.log(fields)}>Log fields</button>
</div>
);
};
export default App;
have multiple solutions to this problem for example:
Solution #1
Using useRef to store value of the field
import { useRef, useCallback } from "react";
export default function App() {
const fullNameInputElement = useRef();
const emailInputElement = useRef();
const passwordInputElement = useRef();
const passwordConfirmationInputElement = useRef();
const formHandler = useCallback(
() => (event) => {
event.preventDefault();
const data = {
fullName: fullNameInputElement.current?.value,
email: emailInputElement.current?.value,
password: passwordInputElement.current?.value,
passwordConfirmation: passwordConfirmationInputElement.current?.value
};
console.log(data);
},
[]
);
return (
<form onSubmit={formHandler()}>
<label htmlFor="full_name">Full name</label>
<input
ref={fullNameInputElement}
id="full_name"
placeholder="Full name"
type="text"
/>
<label htmlFor="email">Email</label>
<input
ref={emailInputElement}
id="email"
placeholder="Email"
type="email"
/>
<label htmlFor="password">Password</label>
<input
ref={passwordInputElement}
id="password"
placeholder="Password"
type="password"
/>
<label htmlFor="password_confirmation">Password Confirmation</label>
<input
ref={passwordConfirmationInputElement}
id="password_confirmation"
placeholder="Password Confirmation"
type="password"
/>
<button type="submit">Submit</button>
</form>
);
}
or still use useState but store all values in one object
import { useState, useCallback } from "react";
const initialUserData = {
fullName: "",
email: "",
password: "",
passwordConfirmation: ""
};
export default function App() {
const [userData, setUserData] = useState(initialUserData);
const updateUserDataHandler = useCallback(
(type) => (event) => {
setUserData({ ...userData, [type]: event.target.value });
},
[userData]
);
const formHandler = useCallback(
() => (event) => {
event.preventDefault();
console.log(userData);
},
[userData]
);
return (
<form onSubmit={formHandler()}>
<label htmlFor="full_name">Full name</label>
<input
id="full_name"
placeholder="Full name"
type="text"
value={userData.fullName}
onChange={updateUserDataHandler("fullName")}
/>
<label>Email</label>
<input
id="email"
placeholder="Email"
type="email"
value={userData.email}
onChange={updateUserDataHandler("email")}
/>
<label htmlFor="password">Password</label>
<input
id="password"
placeholder="Password"
type="password"
value={userData.password}
onChange={updateUserDataHandler("password")}
/>
<label htmlFor="password_confirmation">Password Confirmation</label>
<input
id="password_confirmation"
placeholder="Password Confirmation"
type="password"
value={userData.passwordConfirmation}
onChange={updateUserDataHandler("passwordConfirmation")}
/>
<button type="submit">Submit</button>
</form>
);
}
Solution #2
Or you have multiple libraries that also provide solutions like react-form-hook https://react-hook-form.com/

How to a make dynamic form in React

I'm learning React. My target is to make this object:
"Phones": [
{
"Type": "Mobile",
"Phone_Number": "6546543"
},
{
"Type": "Home",
"Phone_Number": "6546543"
}
]
I did some research and I followed this YouTube video ReactJS - Dynamically Adding Multiple Input Fields.
These values I'll fetch from a form. Th user can keep on adding as many numbers as he wants. My code is:
render() {
return (
<div>
<h1>The Form</h1>
<label>Contact</label>
{this.state.phones.map((phone, index) => {
return (
<div key={index}>
<input onChange={(e) => this.handleChange(e)} value={phone} />
<select>
{this.phoneTypes.map((phoneType, index) => {
return (
<option key={index} value={phoneType}>
{phoneType}
</option>
);
})}
</select>
<button onClick={(e) => this.handleRemove(e)}>Remove </button>
</div>
);
})}
<hr />
<button onClick={(e) => this.addContact(e)}>Add contact</button>
<hr />
<button onClick={(e) => this.handleSubmit(e)}>Submit</button>
</div>
);
}
I'm not pasting the entire code here as I've already created a stackblitz. My code is not working as expected. Please pitch in.
You need to pass index in the handleChange function for input field. I guess you missed that part from video.This will make the input field editable.
<input
onChange={(e) => this.handleChange(e, index)}
value={phone}
/>
For the second part to get the expected object array I have updated some code, please check:
import React, { Component } from 'react';
class Questionnaire extends Component {
state = {
phones: [{ type: '', number: '' }],
};
phoneTypes = ['Mobile', 'Home', 'Office'];
addContact() {
this.setState({ phones: [...this.state.phones, { type: '', number: '' }] });
}
handleChange(e, index) {
this.state.phones[index]['number'] = e.target.value;
this.setState({ phones: this.state.phones });
}
handleRemove(index) {
this.state.phones.splice(index, 1);
console.log(this.state.phones, '$$$');
this.setState({ phones: this.state.phones });
}
handleSubmit(e) {
console.log(this.state, '$$$');
}
render() {
return (
<div>
<h1>The Form</h1>
<label>Contact</label>
{this.state.phones.map((phone, index) => {
return (
<div key={index}>
<input
onChange={(e) => this.handleChange(e, index)}
value={phone.number}
name="number"
/>
<select>
{this.phoneTypes.map((phoneType, index) => {
return (
<option key={index} value={phoneType} name="type">
{phoneType}
</option>
);
})}
</select>
<button onClick={(e) => this.handleRemove(e)}>Remove </button>
</div>
);
})}
<hr />
<button onClick={(e) => this.addContact(e)}>Add contact</button>
<hr />
<button onClick={(e) => this.handleSubmit(e)}>Submit</button>
</div>
);
}
}
export default Questionnaire;
You can use input objects like formik
import { useState } from 'react';
const Component = () => {
const [inputs, setInputs] = useState({ // Initial inputs
email: "",
phoneNumber: "",
});
const handleSubmit = (e) => {
e.preventDefault();
// Do
};
const handleChange = (e) => {
setInputs({...inputs, [e.target.id]: e.target.value});
};
const addInput = () => {
const name = window.prompt("Type a name", "");
setInputs({...inputs, [name]: ""});
};
return (
<form onSubmit={handleSubmit}>
{object.keys(inputs).map((name, i) => {
<input type="text" onChange={handleChange} name={name} value={inputs[name]} />
})}
<button
type="button"
onClick={addInput}
>
Add Input
</button>
</form>
);
}

React - how to use map to pass an array of options on input of type unform select

I have a select input where I want to pass an options array object using map but when rendering my page only one option even when the array I'm using in the map has several items it insists on presenting only one
below all the code:
export default function PesquisarAulas() {
const dispatch = useDispatch();
const user = useSelector((state) => state.user.profile);
const [docente, setDocente] = useState([]);
const [docenteDisciplinas, setDocenteDisciplinas] = useState([]);
const [disciplinas, setDisciplinas] = useState([]);
const updateDisciplinas = [...disciplinas];
async function carregarDocente() {
const response = await api.get(`docente/findByUser/${user.id}`);
return response.data;
}
async function carregarDisciplinasDocente() {
const response = await api.get(`docente/${docente.id}/disciplinas`);
return response.data;
}
async function carregarDisciplina(disc) {
const response = await api.get(`disciplinas/${disc.id_disciplina}`);
return response.data;
}
useEffect(() => {
carregarDocente().then((value) => {
setDocente(value);
});
}, [user]);
useEffect(() => {
carregarDisciplinasDocente().then((value) => {
setDocenteDisciplinas(value);
});
}, [docente]);
useEffect(() => {
docenteDisciplinas.map((docDisc) =>
carregarDisciplina(docDisc).then((value) => {
updateDisciplinas.push(value);
setDisciplinas(updateDisciplinas);
})
);
}, [docenteDisciplinas]);
console.log(disciplinas);
function handleSubmit() {}
return (
<Container>
<div className="title">Pesquisar aulas</div>
<Form onSubmit={handleSubmit}>
<div className="input-box">
<span>Ano Letivo:</span>
<Input
name="anoLetivo1"
type="text"
placeholder="Introduza o ano letivo"
/>
</div>
<div className="input-box">
<span>Disciplinas:</span>
<Select
name="tech"
options={disciplinas.map((disciplina) => ({
id: disciplina.id,
title: disciplina.nome,
}))}
placeholder="Nenhum selecionado"
/>
</div>
<div className="input-box">
<span>Aulas de:</span>
<Input name="dataInicio1" type="datetime-local" id="pickup_time" />
<span style={{ marginLeft: '10px' }}>ate:</span>
<Input name="dataFinal1" type="datetime-local" id="pickup_time" />
</div>
<div className="input-box">
<span>Curso:</span>
<Input name="curso1" type="text" placeholder="Introduza o curso" />
</div>
<div className="input-box">
<span>Unidade Curricular:</span>
<Input
name="unidadeCurricular1"
type="text"
placeholder="Introduza a unidade curricular"
/>
</div>
<hr />
<button type="submit">Pesquisar</button>
</Form>
</Container>
);
}
the focus of the problem is on these two code snippets here:
const [disciplinas, setDisciplinas] = useState([]);
const updateDisciplinas = [...disciplinas];
useEffect(() => {
docenteDisciplinas.map((docDisc) =>
carregarDisciplina(docDisc).then((value) => {
updateDisciplinas.push(value);
setDisciplinas(updateDisciplinas);
})
);
}, [docenteDisciplinas]);
<Select
name="tech"
options={disciplinas.map((disciplina) => ({
id: disciplina.id,
title: disciplina.nome,
}))}
placeholder="Nenhum selecionado"
/>
I think the problem is that when the select is rendered only one item is inserted in the disciplines array,
I think maybe if there was a way to make Select wait until all the items in the disciplines array are ready so it can render, the problem would be solved.
Try using the select like this:
<select placeholder="Nenhum selecionado" >
{{disciplinas.map((disciplina) => {
<option value={disciplina.nome}>
{disciplina.nome}
</option>
})}}
</select>

Conditionally display input field

I am working on form in react. After selecting dish type I want to conditionally display other fields.
For example if I select pizza I want to display number field. If I select soup I want to display other input field.
Here is sample of code:
const Form = () => {
const [dishes] = React.useState([
{
label: "Pizza",
value: "Pizza",
},
{ label: "Soup", value: "Soup" },
{ label: "Sandwich", value: "Sandwich" },
]);
return (
<div>
<form>
<label>Name</label>
<input type="text" required></input>
<label>Preperation Time</label>
<input type="time" step="2" required></input>
<label>Type</label>
<select>
{dishes.map((dish) => (
<option key={dish.value} value={dish.value}>
{dish.label}
</option>
))}
</select>
<button>submit</button>
</form>
</div>
);
};
export default Form;
import React, { useState } from 'react';
function App() {
const [dishes] = React.useState([
{
label: "Pizza",
value: "Pizza",
},
{ label: "Soup", value: "Soup" },
{ label: "Sandwich", value: "Sandwich" },
]);
const [type, setType] = useState([])
const handleChang = (value) => {
setType(value);
}
return (
<div>
<form>
{(type == "Pizza") && (<> <label>Name</label>
<input type="text" required></input></>)
}
{(type == "Soup") && (<> <label>Preperation Time</label>
<input type="time" step="2" required></input></>)
}
<label>Type</label>
<select onChange={(e) => handleChang(e.target.value)}>
{dishes.map((dish) => (
<option key={dish.value} value={dish.value}>
{dish.label}
</option>
))}
</select>
<button>submit</button>
</form>
</div>
);
}
export default App;
Try this (codesandbox: https://codesandbox.io/s/vigilant-kepler-5xuio?file=/src/App.js)
const [dishes] = React.useState([
{
label: "Pizza",
value: "Pizza",
field: (
<div>
<label htmlFor="pizza">Toppings</label>
<input type="number" id="pizza" />
</div>
)
},
{
label: "Soup",
value: "Soup",
field: (
<div>
<label htmlFor="soup">How soupy?</label>
<input type="range" id="soup" />
</div>
)
},
{
label: "Sandwich",
value: "Sandwich",
field: (
<div>
<label htmlFor="sandwich">Enter your ingredients</label>
<input type="text" id="sandwich" />
</div>
)
}
]);
const [selectedDish, setSelectedDish] = React.useState(dishes[0]);
const handleDishSelect = (e) => {
const dish = dishes.find((dish) => dish.value === e.target.value);
if (dish) {
setSelectedDish(dish);
}
};
return (
<div>
<form>
<label>Name</label>
<input type="text" required></input>
<label>Preperation Time</label>
<input type="time" step="2" required></input>
<label>Type</label>
<select onChange={handleDishSelect}>
{dishes.map((dish) => (
<option key={dish.value} value={dish.value}>
{dish.label}
</option>
))}
</select>
{selectedDish && selectedDish.field}
<button>submit</button>
</form>
</div>
);
So you wanna display some JSX on condition right?
you can just check the condition and select a output as if condition
<div>
{dishes.value.equals("pizza") && (<input type="number">)}
{dishes.value.equals("soup") && (<input type="text">)}
</div>
You can use Ternary operation to if else condition
<div>
{dishes.value.equals("pizza") ? (<input type="number">) : (<input type="text">)}
</div>
This is the architecture I would follow (see below). First define your menu, which I presume is not changing so should just be a plain object. Then split you code in a few components:
MenuForm - this can be your main menu form component;
MenuItem - this is a component that generates selection options for a menu item
Crete additional components to handle the specifics of each menu item, say PizzaItemMenu, SoupItemMenu, etc.
Here is a full example app in action based on your code:
const menu = {
pizza: {
type: [
{
label: 'neapolitana',
value: 'npa'
}, {
label: 'chicago',
value: 'ccg'
}, {
label: '4-cheese',
value: 'cse'
}],
number: 1,
addOn: false
},
soup: {
type: [{
label: 'carrot',
value: 'crt'
}, {
label: 'potato',
value: 'ptt'
}],
number: 1,
addOn: false
}
}
const MenuForm = () => {
const [menuItem, setMenuItem] = React.useState(false);
const handleMenuItemSelection = (e) => {
setMenuItem(e.target.value);
}
const additionalMenuItemSelections = () => {
switch (menuItem) {
case 'pizza':
return <PizzaItemMenu />
case 'soup':
return <SoupItemMenu />
default:
return false;
}
}
return (
<div>
<form>
<label>Name</label>
<input type="text" required></input>
<label>Preperation Time</label>
<input type="time" step="2" required></input>
<label>Type</label>
<select className='menu' onChange={handleMenuItemSelection} defaultValue='x'>
<option disabled value="x">Select menu item</option>
{Object.keys(menu).map((item, index) => {
return (
<option key={index} value={item}>{item}</option>
)
})}
</select>
{additionalMenuItemSelections()}
<button>submit</button>
</form>
</div>
);
};
const PizzaItemMenu = () => {
const [pizzaType, setPizzaType] = React.useState(false);
const handleSelection = (e) => {
const data = e.target.value;
setPizzaType(data);
}
return (
<div className='soup-menu'>
<p>You've selected pizza!</p>
<MenuItem menuItem='pizza' handleSelection={handleSelection} />
Additional form menu selection options for pizzas goes here
{pizzaType && <p>You've selected {pizzaType} pizza!</p>}
</div>
)
}
const SoupItemMenu = () => {
const [soupType, setSoupType] = React.useState(false);
const handleSelection = (e) => {
const data = e.target.value;
setSoupType(data);
}
return (
<div className='soup-menu'>
<p>You've selected soup!</p>
<MenuItem menuItem='soup' handleSelection={handleSelection} />
Additional form menu selection options for soups goes here
{soupType && (<p>You've selected {soupType} soup!</p>)}
</div>
)
}
const MenuItem = ({ menuItem, handleSelection }) => {
const itemOptions = menu[menuItem].type;
return (
<select id={menuItem} defaultValue='x' onChange={(e) => handleSelection(e)} >
<option disabled value="x">Select {menuItem} type</option>
{itemOptions.map((itemKey, index) => (
<option key={index} value={itemKey.value}>{itemKey.label}</option>
))}
</select>
)
}
export default MenuForm;

React not rendering after update state object

I update my state object after changing the value of a select. It's setting the correct values to the object, but not updating in the browser (the input fields).
import React, { useState, useEffect } from 'react';
import { Controller, useForm } from "react-hook-form";
import { Button, Form, Label, Input, Alert } from 'reactstrap';
import NumberFormat from 'react-number-format';
// More imports
const AddUser = (props) => {
const propID = props.propID;
// The object has more properties. I'm just showing the ones related to the issue
const [ addUser, setAddUer ] = useState({
unitID: 0,
adminFee: 0
});
const [ units, setUnits ] = useState([]);
useEffect(() => {
async function fetchData() {
// this method is an axios request to grab data
const data = await myAxios.getUnits(propID);
setUnits(data);
}
fetchData();
}, [propID]);
const handleUnitChange = async (id) => {
const unitCharges = await myAxios.getUnitCharges(parseInt(id));
if(unitCharges !== null) {
setAddUer ({
...addUser,
unitID: id,
adminFee: parseFloat(unitCharges.AdminFee).toFixed(2)
});
}
}
// There is a lot of other fields and style here.
// I'm showing just the related fields
return (
<>
<Label for="unit" className="mr-sm-10">Unit</Label>
<Input type="select" name="unit" id="unit"
value={addUser.unitID} onChange={(e) => handleUnitChange(e.target.value)}
innerRef={register({ required: true })}
>
<option value="0">Select</option>
{units.map((obj) => {
return (
<option
key={obj.UnitID}
value={obj.UnitID}
>
{obj.UnitName}
</option>
);
})}
</Input>
<Label for="admin" className="mr-sm-10">Admin</Label>
<Controller
as={
<NumberFormat
thousandSeparator={true}
prefix={"$"}
onValueChange={(v) => {
setAddUer({...addUser, adminFee: v.floatValue === undefined ? 0 : v.floatValue})
}}
/>
}
name="admin"
id="admin"
variant="outlined"
defaultValue={addUser.adminFee}
getInputRef={register({ required: true })}
control={control}
className="form-control"
/>
</>
);
};
export default AddUser;
SandBox with array instead of Axios request: https://codesandbox.io/s/weathered-star-3i9u4?file=/src/App.js
Please try to replace the Controller part of your code with the following code.
<Controller
name="admin"
id="admin"
variant="outlined"
getInputRef={register({ required: true })}
control={control}
className="form-control"
value={addUser.adminFee}
render={({ field }) => (
<NumberFormat
thousandSeparator={true}
prefix={"$"}
value={addUser.adminFee}
onValueChange={(v) => {
setAddUer({
...addUser,
adminFee: v.floatValue === undefined ? 0 : v.floatValue
});
}}
/>
)}
/>

Resources