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

225
Vistas
React: having trouble making file viewer

Ok, so I'm creating a personal blog, and want it easy for me to upload files to the server and then retrieve them for my posts when writing, to that end I'm trying to more or less create a simple file explorer that dumps all the uploaded files in a div, wrapping them in the appropriate tag (img, audio, video etc.) so my solution is to create a function that retrieves a blob from a url, determines the mime type, and then sets the html element it returns based on that type:

const Media = ({ src = '' }) =>
{
    let [ elem, setElem ] = useState(<div/>);
    axios.get(
        `/static/uploads/${ src }`,
        { responseType: 'blob' }
    ).then(blob =>
    {
        const type = blob.data.type.split('/')[0];
        switch (type)
        {
            case 'image':
                setElem(<img src={ URL.createObjectURL(blob.data) }/>);
                break;
        }
    });
    return elem;
};

unfortunately, nothing's being displayed in my explorer (or rather dumping ground):

<div className='gallery'>
    { files.map(name => (<Media src={ name }/>)) }
</div>

this retrieves the filenames:

axios.get('/api/upload').then(uploads =>
{
    setFiles(uploads.data.files);
});

... and it freezes my (rather old) laptop after a while to boot. What am I doing wrong?

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

0

So, I finally found the solution... and I'm embarrassed to say it's quite trivial due a rookie mistake. The code managing the state needs to be asynchronous and handled by useEffect due to being run in the render cycle, otherwise it eventually crashes (as well as block things like user interaction due to the page constantly rendering):

const Media = ({ src = '' }) =>
{
    const [ elem, setElem ] = useState(<div/>);
    useEffect(async () =>
    {
        const blob = await axios.get(
            `/static/uploads/${ src }`,
            { responseType: 'blob' });
        const type = blob.data.type.split('/')[0];
        switch (type)
        {
            case 'image':
                setElem(<img src={ URL.createObjectURL(blob.data) }/>);
                break;
        }
    }, []);
    return elem;
};
useEffect(async() =>
{
    const uploads = await axios.get('/api/upload');
    setFiles(uploads.data.files);
}, []);

... y ya

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