Select option value returns '[object Object]' - reactjs

I would like to ask for your help. I have mapped a list of data patientOptions to select field, each option has a value of
value: {
id: patient.id,
firstName: patient.firstName,
middleName: patient.middleName,
lastName: patient.lastName,
},
I need to store this information when I submit the form. If I console.log(patientOptions) this will appear
What I am trying to achieve is to get all values
value: {
id: 13412341234,
firstName: John,
middleName: Made,
lastName: Doe,
},
But if I will try to submit the form and log it to the console this will show up.
I have also tried just getting the value of 1 object it works but trying to get the value of multiple objects still returns the same error
Here is the rest of the code I hope anyone can help me.
const patientOptions = patient.map((patient) => ({
key: `${patient.firstName} ${patient.middleName} ${patient.lastName},
value: {
id: patient.id,
firstName: patient.firstName,
middleName: patient.middleName,
lastName: patient.lastName,
},
}));
onSubmit = (values) =>
console.log("form data", {
patient: values.patient,
});
<Formik
initialValues={{
patient: "",
}}
onSubmit={onSubmit}
>
<Form>
<FormikControl
control="select"
name="patient"
label="Patient"
options={patientOptions}
/>
</Form>
</Formik>;

Related

How to set a value of nest object value in onChange event

I'm trying to set a value of nested object value for the onChange event.
const [state, setState] = useState({
fullname: '',
email:
address: {
fhbca: '',
street: '',
landmark: '',
pincode: '',
}
});
onChange={(e) => { setState({...state, address.fhbca : e.target.value }) }} **<--**
When setting the value of address.fhbca. Using this above statement throws errors Accounts.jsx: Unexpected token, expected "," (120:100). Please correct me and suggest.
how to set a value of this address.fhbca ..?
You need to do like this
onChange={(e) => { setState(({...state, address: {...state.address, fhbca: e.target.value} }})}}

How to submit a formik form with two similar fields

I have a form and on this form there is an Add another form button which adds another form with the same field. I am using fieldArray by formik. Currently if I add another form then submit it's only submitting the values of the first form not the second. How can I ensure that all the form index fields are submitted.
Here's the code
const initialValues = {
certificationItems: [
{
name: '',
description: '',
additionalDetails: '',
isThirdParty: thirdParty,
issueDate: '',
expirationDate: '',
properties: [
{ name: 'prefillCertification', value: '' },
{ name: 'prefillInfo', value: '' }
]
}
]
};
<Formik
initialValues={initialValues}
onSubmit={(values) => {
console.log('values', index)
operations.updateBinding(['name'], values.certificationItems[0].name);
operations.updateBinding(['description'], values.certificationItems[0].description);
operations.updateBinding(['additionalDetails'], values.certificationItems[0].additionalDetails);
operations.updateBinding(['isThirdParty'], values.certificationItems[0].isThirdParty);
operations.updateBinding(['issueDate'], values.certificationItems[0].issueDate);
operations.updateBinding(['expirationDate'], values.certificationItems[0].expirationDate);
operations.submit();
}}

How to use Formik with React-Select with isMulti?

I'm building a system where we can create a project and assign it to several users by filling up a form using Formik, Yup and React-Select.
However, I'm really struggling with passing the array of users when submitting my form using Formik, Formik doesn't receive the data from React-Select.
Here are snippets of the code:
const validationSchema = () => {
return Yup.object().shape({
title: Yup.string().required('A title is required'),
description: Yup.string().required('A description is required'),
assigned: Yup.array().required('At least one assigned user is required'),
});
};
const formik = useFormik({
initialValues: {
title: '',
description: '',
assigned: [],
},
validationSchema,
validateOnBlur: false,
validateOnChange: false,
onSubmit: (data) => {
ProjectService.create(data).then(() => {
navigate('/projects');
window.location.reload();
});
},
});
The component containing the options to select:
Assign to:
<SelectList
name="users"
options={convertToReactSelectObject(users)}
onChange={(assignedUsers) =>
formik.setFieldValue('assigned', assignedUsers.value)
}
value={formik.values.assigned}
/>
{formik.errors.assigned ? formik.errors.assigned : null}
Does someone have an idea of what I should fix to make it work?
Thank you!
My mistake was that I was trying to only pass the "value" field of the array to Formik which doesn't work. So I've passed the whole array of assigned users
<SelectList
options={convertToReactSelectObject(users)}
value={formik.values.assigned}
onChange={(assignedUser) =>
formik.setFieldValue('assigned', assignedUser)
}
/>
Then on the backend, the new project will only take the value field of the assigned users.
// Create a Project
const project = new Project({
title: req.body.title,
description: req.body.description,
assigned: req.body.assigned.map((e) => e.value),
});

How to deal with optional field input in React controlled forms

Let's say I have a form with 3 fields: firstName, middleName, lastName. The fields firstName and lastName are mandatory, but middleName is optional. So, when someone completes the form without writing his middle name, the object that is produced by the form is something like
{
firstName: "John",
middleName: "",
lastName: "Doe",
}
but I would like to get something like
{
firstName: "John",
middleName: undefined,
lastName: "Doe",
}
Of course I could manually clean the resulting object, and convert "" to undefined, but I wonder if there is a better way.
You can write custom logic to handle this:
const initialValues = {
firstName: "",
lastName: "",
middleName: ""
}
// Set use state
const [values, setValues] = useState(initialValues);
const handleMiddleNameInputChange = (event) => {
event.persist();
if(middleName === ""){
setValue((values)=>({
...values,
middleName: "undefined"
}));
}else{
setValues((values) => ({
...values,
middleName: event.target.value,
}));
}
};

State is not updating with correct information

Hello I am trying to update the vale of my state in React but I don't know why it always goes to the option where selectedUser is not defined. I tried putting everything inside an if-else but I got the same results, the strange thing is that when I wrote something in the console it went inside my conditional but it took the empty values instead.
const [inputFieldState, setInputFieldState] = useState(InputFields(selectedUser));
function InputFields(selectedUser: any) {
return selectedUser
? selectedUser
: {
email: "",
firstName: "",
lastName: "",
customerId: "",
id: "",
role: ""
};
}
selectedUser is a fake value for now
return {
firstName: planes[Math.floor(Math.random() * planes.length)],
lastName: planes[Math.floor(Math.random() * planes.length)],
customerId: planes[Math.floor(Math.random() * planes.length)],
id: planes[Math.floor(Math.random() * planes.length)],
role: names[Math.floor(Math.random() * names.length)],
email: Math.ceil(Math.random() * 5)
};
when I do a console log of the selected user I get
{firstName: "x-wing", lastName: "Winnebago", customerId: "y-wing", id: "TIE-fighter", role: "Anakin", …}
customerId: "y-wing"
email: 2
firstName: "x-wing"
id: "TIE-fighter"
lastName: "Winnebago"
role: "Anakin"
From the comments, selectedUser is a function
const [inputFieldState, setInputFieldState] = useState(InputFields(selectedUser()));
function InputFields(user: any) { // just changed the name to avoid potential confusion
return user
? user
: {
email: "",
firstName: "",
lastName: "",
customerId: "",
id: "",
role: ""
};
}
I think you need to change useState(InputFields(selectedUser)) to
useState(() => InputFields(selectedUser))
so that it will not use the Initial state in every render

Resources