Reputation: 307
I'm trying to upload a file to Cloudinary and save this file to a MongoDb database. The upload is working (I can see the new image in my Cloudinary account), but the db is not updated. The back end is built with Express. This is my code:
React function:
const { user, updateUser } = useContext(AuthContext)
const [imageUrl, setImageUrl] = useState("")
const navigate = useNavigate()
useEffect(() => {
axios
.get(`${API_URL}/users/user/${user._id}`)
.then(response => {
const { imageUrl } = response.data
setImageUrl(imageUrl)
})
.catch(err => console.log(err))
}, [user._id])
const handleFileUpload = e => {
e.preventDefault()
const uploadData = new FormData()
uploadData.append("imageUrl", e.target.files[0])
service
.uploadImage(uploadData)
.then(res => {
setImageUrl(res.secure_url)
})
.catch(err => console.log(err))
}
const handleSubmit = e => {
e.preventDefault()
const requestBody = { imageUrl }
if (imageUrl === "") {
return
}
axios
.put(`${API_URL}/users/edit-picture/${user._id}`, requestBody)
.then(res => {
updateUser(res.data)
navigate("/my-account")
})
.catch(err => console.log(err))
}
JSX:
<Form
onSubmit={handleSubmit}
>
<Input
type="file"
id="imageUrl"
onChange={handleFileUpload}
/>
<Button type="submit">Send</Button>
</Form>
updateUser function:
const updateUser = updatedUser => {
localStorage.setItem("user", JSON.stringify(updatedUser))
setUser(JSON.parse(localStorage.getItem("user")))
}
uploadImage function:
const uploadImage = file => {
return axios
.put(`${API_URL}/users/upload-picture`, file)
.then(res => res.data)
.catch(errorHandler)
}
And for the backend (where fileUploader is the Cloudinary config file):
router.put(
"/upload-picture",
fileUploader.single("imageUrl"),
(req, res, next) => {
if (!req.file) {
next(new Error("No file uploaded"))
return
}
res.json({ secure_url: req.file.path })
}
)
router.put("/edit-picture/:id", (req, res, next) => {
const { imageUrl } = req.body
const id = req.params.id
console.log(id)
User.findByIdAndUpdate(id, { imageUrl }, { new: true })
.then(updatedUser => {
res.status(200).json(updatedUser)
})
.catch(err => next(err))
})
Thanks for your help!
Upvotes: 0
Views: 163
Reputation: 15
There seems to be some issue with your mongodb connection
Upvotes: 0