I'm using react-colors and I'm trying to post a product but I'm getting a response with the field color: [object Object].
This is my color in product model:
color: { type: Array },
This is my newproductpage.jsx where i handle form submit:
const handleSubmit = e => {
e.preventDefault();
const myForm = new FormData();
myForm.set('name', name);
myForm.set('price', price);
myForm.set('description', description);
myForm.set('quantity', quantity);
myForm.set('category', category);
myForm.set('size', size);
myForm.set('color', colors);
images.forEach(image => {
myForm.append('images', image);
});
dispatch(createProduct(myForm));
};
This function save color in my colors state:
const saveColors = color => {
const filtered = colors.filter(clr => clr.color !== color.hex);
setColors([...filtered, { color: color.hex }]);
};
When i console.log(colors)
im getting:
Array [ {…} ] 0: Object { color: "#fcb900" } color: "#fcb900"
And thats okay. When i publish post my all fields are okay, just colors: [object Object]
This is my color in form:
<Form.Group className='mb-3'>
<Form.Label>Product Color</Form.Label>
{colors.length > 0 && <h1>colors list</h1>}
{colors.length > 0 &&
colors.map((color, i) => (
<div
className='p-3 me-2 rounded d-inline-block'
key={color.i}
style={{ background: color.color }}
onClick={() => deleteColor(color)}
></div>
))}
<TwitterPicker onChangeComplete={saveColors} />
</Form.Group>
How to solve this
CodePudding user response:
As I see, your colors is an array of objects so you should send them with the proper way in FormData.
- using JSON.stringify and handle the string data in the backend:
myForm.append('color', JSON.stringify(colors));
- Send as an array in FormData:
for (let i = 0; i < colors.length; i ) {
myForm.append('colors[]', colors[i]);
}