Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Push ids in an array in react

I want to save an array of object ids in the database but it receives as a plain string from the frontend. the useState hook: const [package_ids, setPackage_Ids] = useState([]); I am appending this ids in the formdata: formData.append("package_ids", package_ids); The code where admin selects the packageIds:

<Form.Group controlId="package_ids">
   <Form.Label>Select Package/s:</Form.Label>
   {packages.map((item) => (
     <Form.Check
       key={item._id}
       type="checkbox"
       label={item.name}
       onChange={(e) =>
         setPackage_Ids((c) =>
           e.target.checked
            ? [...c, item._id]
            : c.filter((el) => el !== item._id)
         )
       }
     />
   ))}
</Form.Group>

If I log the packageids in the front-end it logs as an array and in the backend I am using app.use(express.json())

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You cannot send an array/object to form data directly. Form data only receives primitive data types like number or string.

In this case, you can use JSON.stringify to convert it to string-typed data.

formData.append("package_ids", JSON.stringify(package_ids));

Your server will receive package_ids as a string, so you need to parse it back to your original data by

const originalData = JSON.parse(package_ids);

If you are concerned that the above approach makes your data hard to read, you also can use the string join (for the client-side) and split (for the server-side)

Client-side

const packageIds = package_ids.join(",") //"1,2,3"

Server-side

const packageIds = package_ids.split(",") //["1","2","3"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading