'React / useState (complex) - dynamic input fields and fecthed data
I've problems with binding a config object for a list of input fields and fetched data from api. Restore the input changes to useState and restore fetch data from api to useState.
onChange: change the input value in the useState data and show the information in the input field.
onFetch: i get a simple api resonse with key and value. This response should show at the input fields.
import React from 'react';
interface InputInterface {
key: string,
label: string,
value: any
}
const input_array: Array<InputInterface> = [
{ key: 'userid', label: 'User ID', value: '' },
{ key: 'firstname', label: 'Firstname', value: '' },
{ key: 'lastname', label: 'Lastname', value: '' },
{ key: 'department', label: 'Department', value: 'NI' },
{ key: 'location', label: 'Location', value: '' }
];
const simulated_fetch: any = {
userid: 12544,
firstname: 'John',
lastname: 'Doe',
department: 'New York',
location: 'Brooklyn'
}
export const DynamicForm = () => {
const [inputlist, setInputlist] = React.useState<Array<InputInterface>>(input_array);
const onChangeInput = (e: any, key: string) => {
// setInputlist({ // something like this
// ...inputlist,
// [key]: e.target.value
//});
}
const onFetch = () => {
// setInputlist(simulated_fetch); // something like this
}
return (
<div>
<form>
{inputlist.map((item: InputInterface, index: number) => (
<div key={index}>
<label>{item.label}</label>
<input value={item.value} onChange={(e) => { onChangeInput(e, item.key) }} />
</div>
))}
</form>
<button onClick={() => { onFetch() }}>Simulate Fetch</button>
</div>
);
}
Solution 1:[1]
I am not familiar with typescript but i think this js code help you out ,hope this is what you are looking for .
const onChangeInput = (e: any, key: string) => {
const inList = [...inputlist];
inList.forEach((ele)=>{
ele.key === key ? (ele.value = e.target.value): '';
})
setInputlist(inList);
}
const onFetch = () => {
const inList = [...inputlist];
inList.forEach((ele)=>{
ele.value = simulated_fetch[ele.key];
})
setInputlist(inList);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | karthik rao |
