Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda