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

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

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