I'm trying to do aa react form using react-hook-forms, but I'm having trouble presenting data retrieved from an API call.
I've sort of combined this example , which deals with asynchronously setting form values, and this example , which deals with nested arrays.
But for the life of me, I simply could not get it to work. The JSON output of the API is something like this:
{"daily": { "last_received_date": "2020-08-03 11:04:18 UTC+8", "tasks": [
{ "id": "1", "freq": "d", "prog": 0, "max": 5, "reward": 1000 },
{ "id": "2", "freq": "d", "prog": 0, "max": 1, "reward": 1000 },
{ "id": "3", "freq": "d", "prog": 0, "max": 3, "reward": 1000 }]},
"weekly": {/*Similar to daily*/}}
Here's the functional component:
const UserTaskForm = (data) => {
const [TaskId, setTaskId] = useState();
const [TaskArray, setChallengeArray] = useState([]);
const { register, control, handleSubmit, getValues, reset, errors } = useForm();
const onSubmit = (formData) => {console.log(formData);};
useEffect(() => {
async function fetchData() {
try {
let result = await dbGetUserTasks(data.userId);
console.log(result);
const tempArray = [];
const formData = JSON.parse(result[0].challenges);
tempArray.push(formData.daily);
tempArray.push(formData.weekly);
setTaskId(JSON.parse(result[0].id));
setChallengeArray(tempArray);
} catch (error) { console.error(error); }
}
fetchData();
}, []);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Box paddingTop={2} paddingBottom={2}>
<Button type="submit" style={{ marginLeft: "auto" }}>Save Changes</Button>
</Box>
{TaskArray ? <Spinner animation="border" /> : <TaskTypeCards{...{ control, register, TaskArray, getValues, errors }} />}
</form>
);
}
export default UserTaskForm;
And here's the functional component that calls:
export default function TaskTypeCards({ control, register, defaultValues, errors }) {
console.log(defaultValues); // <--------------- Undefined.
const { fields, append, remove } = useFieldArray({ control, name: "test" });
useEffect(() => {
console.log(defaultValues); // <--------------- Undefined.
}, [defaultValues])
return(
{defaultValues.map((challenge, index) => {
return (
<Card>
Blah blah this doesn't work anyway
</Card>
)
})}
)
}
I understand that the components are rendered before the useEffect is fired in UserTaskForm
, but how do I re-render it, such that defaultValues
in TaskTypeCards
don't log out an undefined
?
defaultValues
need to be passed as the props, to receive it as props in the TaskTypeCards components.
Thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.