I have the following data generated by an API:
{
"config": {
1: {"slot1": "SK_DISENGAGE"},
2: {"slot1": "SK_DISENGAGE"}
}
}
I transformed config
into this array of objects below, as it's easier to deal with when displaying it via react-hook-form, and because the items in the object are subject to change:
{
"config": [
{"slot1": "SK_DISENGAGE", element: 1},
{"slot1": "SK_DISENGAGE", element: 2}
]
}
Here's a codesandbox of the code below:
function App() {
const { register, control, handleSubmit, reset, watch } = useForm({
defaultValues: {
config: [
{ slot1: "SK_DISENGAGE", element: 1 },
{ slot1: "SK_DISENGAGE", element: 2 }
]
}
});
// Simplified. The data comes from an API, and useForm would be empty until after the async functions are done.
const { fields } = useFieldArray({ control, name: "config" });
const onSubmit = (data) => console.log("data", data);
renderCount++;
return (
<form onSubmit={handleSubmit(onSubmit)}>
<h1>Field Array </h1>
{fields.map((item, index) => {
return (
<li key={item.id}>
{`Item:`}
<input
name={`config.${item.element}.slot1`}
defaultValue={`${item.slot1}`}
ref={register()}
/>
</li>
);
})}
</ul>
<input type="submit" />
</form>
);
}
However, I'm having trouble transforming it back, and it ends up like this:
{
"config": [
null,
{ "slot1": "SK_DISENGAGE" },
{ "slot1": "SK_DISENGAGE" }
]
}
config
is now an array of objects, a format the API will not take kindly to. I've tried modifying the name
field in the input
tag, adding "
, '
, or no quotes to item.element
, but the results are the same.
I assume the first element is null because nothing is setting the element 0.
How do I programmatically set a number as an object key? Is there a slash or something I should put in so it should be taken as a string?