Home > Back-end >  Push ids in an array in react
Push ids in an array in react

Time:09-27

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())

CodePudding user response:

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"]
  • Related