'ReactJS / Axios / Django: Update form with the current image from API
I'm trying to create an update form in React, the update works fine as I have set the default values that coming from (get method) using axios and set them as the default if none changed. I get the existing image from API and set it as default value in React update form, if image updated get the new one(this one is working fine) if image was not updated, put the existing image that was received from the API which is not working, I get this message:
{image: ["The submitted data was not a file. Check the encoding type on the form."]}
my code:
React:
export function ProductUpdate() {
const [p, setProduct] = useState("")
const {slug} = useParams()
useEffect(() => {
function featchProduct() {
axios.get(API.products.retrive(slug))
.then(res => {
setProduct(res.data)
})
}
featchProduct()
} ,[])
const [loading, setLoading] = useState(false)
const [title, setTitle] = useState("")
const [image, setImage] = useState(null)
const [description, setDescription] = useState("")
const [price, setPrice] = useState("")
const [active, setActive] = useState("")
const [soldout, setSoldout] = useState("")
const handleSubmit = (event) => {
event.preventDefault();
let formField = new FormData()
formField.append('title', title || p.title)
formField.append('slug', slug)
formField.append('description', description || p.description)
formField.append('price', price)
formField.append('active', active)
formField.append('soldout', soldout)
formField.append('image', image || p.image)
axios.put(API.products.update(slug), formField)
.then((res => {
console.log(res.data)
}))
}
API data:
active: true
description: "1"
image: "http://127.0.0.1:8888/media/product_images/5000_IJFmXgH.png"
price: 1111
slug: "p232323"
soldout: true
title: "Product Name"
Image form
<Form.Control
type="file"
name="image"
onChange={(e) => setImage(e.target.files[0])}
/></Form.Group>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|