How to set constant value

Asked

Viewed 37 times

1

I’m using the React-Dropzone package to upload imgages

Now I would like after loading the data from the server, I would like to set an image that came from the data search in the React-Dropzone

How I’m trying:

const Banner = () => {
   const [ img1, setImg1 ] = useState()
   const [formData, setFormData] = useState({
        titulo: '',
        subtitulo: '',
        descricao: '',
        slogan: ''
    })
    
    useEffect(()=>{
        api.get('/api/v1/banner/1')
           .then( response =>{
               setFormData( response.data )
               if( response.data.imagem1 != null ){
                   let string = `http://localhost:3001/foto/${response.data.imagem1}`
                   console.log('url', string);
                   
                   setImg1( string )
               }       
           })
    },[])

  return (
          <div className="form-group">
                        <label htmlFor="descricao">Imagem 1</label>
                        <Dropzone  onFileUploaded={setSelectedFile1} fileFromUrl={img1}/>
                    </div>
   )
}

The data loads, but the string is sent to the Dropzone via the function fileFromUrl is sending before fetching the data.

In the Dropzone I’m trying to do like this:

const Dropzone = ( {onFileUploaded, fileFromUrl} ) =>{
    const [selectedFileUrl, setSelectedFileUrl] = useState('')
   
    useEffect(()=>{
        console.log( 'dropzone', fileFromUrl);
        if( fileFromUrl != undefined ){
            
            setSelectedFileUrl( fileFromUrl )
        }
    },[])

How do I get the variable value fileFromUrl inside Dropzone and show the image?

  • I don’t understand!!!!?

1 answer

3


I don’t know if I really understood your problem... Apparently the value of the state isn’t changing because your useEffect only runs when the component is mounted, you need to make it run when the value of fileFromUrl change.

Example:

useEffect(() => {
  if (!!fileFromUrl) {
    setSelectedFileUrl(fileFromUrl);
  }
}, [fileFromUrl]);
  • It worked. I asked you one thing, you solved two rsrs Thank you!

  • Perfect! I’m glad it worked out.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.