'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?
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | K. Russell Smith |
