Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda