How to work with an array of objects using one input field? Is it possible? #9513
Unanswered
Calebsworld
asked this question in
Ideas
Replies: 1 comment 1 reply
-
impossible to read, could you share a csb? |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I am going to show some code that will explain what I am trying to do.
As you can see I am using useState from React and a button which updates the state. I want to see if I can avoid using useState and just utilize useFieldArray from RHF. I would like to have a button which adds a tag and resets the input, and if the array of tags is empty then display a message using the errors prop from RHF. Is this a possibility?
export const WriteBlogForm = () => {
const queryClient = new useQueryClient()
const [tag, setTag] = useState('');
const [tagsList, setTagsList] = useState([]);
let navigate = useNavigate();
const {
handleSubmit,
formState,
control,
reset
}
= useForm({
mode: 'onChange',
resolver: yupResolver(writeBlogSchema),
defaultValues: {
title: '',
content: '',
image: '',
}
});
const { errors } = formState;
const addTagToTagsArray = tag => {
if (tag.length > 0) {
const id = uuidv4();
const tagObject = { id, name: tag }
setTagsList([...tagsList, tagObject])
setTag('')
}
}
const removeTagFromTagsArray = tag => {
const filteredArray = tagsList.filter(t => tag !== t)
setTagsList(filteredArray)
}
const resetFormState = () => {
setTag('')
setTagsList([])
reset();
}
const createFormDataObj = data => {
const form = document.getElementById('form')
const formData = new FormData(form);
const completeFormData = new FormData();
completeFormData.append('title', formData.get('title'));
completeFormData.append('content', formData.get('content'));
completeFormData.append('image', formData.get('image'));
completeFormData.append('tags[]', JSON.stringify(tagsList))
return completeFormData;
}
const postBlogMutation = useMutation(postBlog, {
onSuccess: () => {
queryClient.invalidateQueries('getAllBlogs')
resetFormState()
navigate('/admin/blogs')
},
})
const onSubmit = async data => {
const fd = createFormDataObj(data)
postBlogMutation.mutate(fd);
}
return (
<Form.Group className="mb-3" controlId="formTitle">
<Form.Label>Title</Form.Label>
<Controller
name='title'
control={control}
render={({ field: { onChange, onBlur, value, name, ref } }) => (
<Form.Control
name={name}
value={value}
onChange={onChange}
onBlur={onBlur}
type="text"
placeholder="Enter title"
isInvalid={errors.title}
/>
)}
/>
{errors.title && <Form.Control.Feedback type="invalid">{errors.title.message}</Form.Control.Feedback>}
</Form.Group>
)
}
Beta Was this translation helpful? Give feedback.
All reactions