Search code examples
javascriptreactjsfile-uploadcloudinary

Why my state value is not changing in react even after changing its state?


I am trying to upload a file on cloudinary through my react component and then fetching its url on successful uploading of file.

Here is my component:

export default function Write() {
  const [file, setFile] = useState(null)
  const [photo, setPhoto] = useState('')
  const postDetails = () => {
    const data = new FormData()
    data.append('file', file)
    data.append('upload_preset', 'mypresetname')
    data.append('cloud_name', 'mycloudname')
    console.log(photo)
    fetch('https://api.cloudinary.com/v1_1/mycloudname/image/upload', {
      method: 'POST',
      body: data,
    })
      .then((res) => res.json())
      .then((data) => setPhoto(data.url))
      .catch((err) => {
        console.log(err)
      })
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    postDetails()
  }

return (<form onSubmit={handleSubmit}>
              <input
                type='file'
                name='file'
                onChange={(e) => setFile(e.target.files[0])}
              /> 
    <button type='submit'> Publish </button></form>)}

when I am trying to do .then((data) => console.log(data.url)) instead of .then((data) => setPhoto(data.url)) i am getting the url correctly but when i am doing .then((data) => (setPhoto(data.url), console.log(photo))) i am getting empty string for photo. Why so when i had setted the value of photo ?

Please help Thanks


Solution

  • setPhoto does not run instantly, it has to rerun the function for the effect to be visible. Try placing console.log(photo) before the return statement.