0

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

1
  • can you provide more details ? like what you get in backend what you get in frontend what is expect in front and back Commented Sep 27, 2022 at 11:20

1 Answer 1

2

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"]
Sign up to request clarification or add additional context in comments.

1 Comment

stackoverflow.com/q/73864232/19773515 here is the another question regarding the file upload in MERN. can you please guide me there?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.