JulSeb42
JulSeb42

Reputation: 307

Why does my upload to Cloudinary works but does not update the database?

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

Answers (1)

gokul nath
gokul nath

Reputation: 15

There seems to be some issue with your mongodb connection

  1. Check wheather you are running mongodb locally and is it working properly
  2. Check the mongodb URL that you would have used in express.Before integrating with react..check the API in postman or some other testing tool.

Upvotes: 0

Related Questions