correct-apricot
correct-apricot5mo ago

Display media on upload

I have the below code and I would like to display the refreshed data (including the new upload) when the image is uploaded. Can this be done with a refine.dev hook or should I use a set state? const {data} = useList<IMedia>({ resource: "media", }); const url = useApiUrl(); const onUpload = async (options: any) => { const {onSuccess, onError, file} = options; const fmData = new FormData(); fmData.append("uploadedFile", file); try { const res = await axios.post( ${url}/media/upload, fmData, { headers: {"content-type": "multipart/form-data"}, withCredentials: true } ); onSuccess("Ok"); } catch (err) { onError({err}); } }; return ( <List> <Space direction="vertical" size={50} style={{width: "100%"}}> <Upload.Dragger name="file" customRequest={onUpload} listType="picture" > </Upload.Dragger> <Image.PreviewGroup preview={{ // Displays the image name countRender: (current) => data?.data[current - 1].id.split("/").at(-1), }}> <Flex wrap="wrap" gap="small"> {data?.data.map((media, index) => ( <Image key={index} width={300} height={300} style={{objectFit: 'cover'}} src={media.srcUrl} /> ))} </Flex> </Image.PreviewGroup> </Space> </List> );
5 Replies
kapa.ai
kapa.ai5mo ago
Hi @BlackBearFTW. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To display the refreshed data (including the new upload) when the image is uploaded, you can use the refetch function from the useList hook provided by refine. This will allow you to refresh the list of media items after a successful upload. Here's how you can modify your code to include the refetch function:
import { useList } from "@refinedev/core";
import axios from "axios";
import { List, Space, Upload, Image, Flex } from "antd";

const MediaUpload = () => {
const { data, refetch } = useList<IMedia>({
resource: "media",
});
const url = useApiUrl();

const onUpload = async (options: any) => {
const { onSuccess, onError, file } = options;

const fmData = new FormData();
fmData.append("uploadedFile", file);
try {
const res = await axios.post(
`${url}/media/upload`,
fmData,
{
headers: { "content-type": "multipart/form-data" },
withCredentials: true
}
);

onSuccess("Ok");
refetch(); // Refresh the data after successful upload
} catch (err) {
onError({ err });
}
};
return (
<List>
<Space direction="vertical" size={50} style={{ width: "100%" }}>
<Upload.Dragger
name="file"
customRequest={onUpload}
listType="picture"
>
</Upload.Dragger>
<Image.PreviewGroup
preview={{
// Displays the image name
countRender: (current) => data?.data[current - 1].id.split("/").at(-1),
}}>
<Flex wrap="wrap" gap="small">
{data?.data.map((media, index) => (
<Image
key={index}
width={300}
height={300}
style={{ objectFit: 'cover' }}
src={media.srcUrl}
/>
))}
</Flex>
</Image.PreviewGroup>
</Space>
</List>
);
};

export default MediaUpload;
import { useList } from "@refinedev/core";
import axios from "axios";
import { List, Space, Upload, Image, Flex } from "antd";

const MediaUpload = () => {
const { data, refetch } = useList<IMedia>({
resource: "media",
});
const url = useApiUrl();

const onUpload = async (options: any) => {
const { onSuccess, onError, file } = options;

const fmData = new FormData();
fmData.append("uploadedFile", file);
try {
const res = await axios.post(
`${url}/media/upload`,
fmData,
{
headers: { "content-type": "multipart/form-data" },
withCredentials: true
}
);

onSuccess("Ok");
refetch(); // Refresh the data after successful upload
} catch (err) {
onError({ err });
}
};
return (
<List>
<Space direction="vertical" size={50} style={{ width: "100%" }}>
<Upload.Dragger
name="file"
customRequest={onUpload}
listType="picture"
>
</Upload.Dragger>
<Image.PreviewGroup
preview={{
// Displays the image name
countRender: (current) => data?.data[current - 1].id.split("/").at(-1),
}}>
<Flex wrap="wrap" gap="small">
{data?.data.map((media, index) => (
<Image
key={index}
width={300}
height={300}
style={{ objectFit: 'cover' }}
src={media.srcUrl}
/>
))}
</Flex>
</Image.PreviewGroup>
</Space>
</List>
);
};

export default MediaUpload;
In this code, the refetch function is called after a successful upload to refresh the list of media items. This ensures that the newly uploaded image is displayed immediately. For more information on using the refetch function, you can refer to the GitHub Issue #1737 (https://github.com/refinedev/refine/issues/1737) where it is discussed. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@490961337896402944> kapa.ai is still learning and improving, please let us know how it did by reacting below
correct-apricot
correct-apricot5mo ago
@kapa.ai this seems very inefficient tho, retrieving all the media
kapa.ai
kapa.ai5mo ago
Let me check the knowledge base for you. One moment! :books: ---------------------- If you want to avoid retrieving all the media again and only update the list with the newly uploaded media, you can manually update the state of your media list. This approach is more efficient as it avoids making an additional request to fetch all media items. Here's how you can modify your code to update the state with the new media item:
import { useState } from "react";
import { useList } from "@refinedev/core";
import axios from "axios";
import { List, Space, Upload, Image, Flex } from "antd";

const MediaUpload = () => {
const { data, refetch } = useList<IMedia>({
resource: "media",
});
const [mediaList, setMediaList] = useState(data?.data || []);
const url = useApiUrl();

const onUpload = async (options: any) => {
const { onSuccess, onError, file } = options;

const fmData = new FormData();
fmData.append("uploadedFile", file);
try {
const res = await axios.post(
`${url}/media/upload`,
fmData,
{
headers: { "content-type": "multipart/form-data" },
withCredentials: true
}
);

onSuccess("Ok");
const newMedia = res.data; // Assuming the response contains the new media item
setMediaList((prevList) => [...prevList, newMedia]); // Update the state with the new media item
} catch (err) {
onError({ err });
}
};
return (
<List>
<Space direction="vertical" size={50} style={{ width: "100%" }}>
<Upload.Dragger
name="file"
customRequest={onUpload}
listType="picture"
>
</Upload.Dragger>
<Image.PreviewGroup
preview={{
// Displays the image name
countRender: (current) => mediaList[current - 1].id.split("/").at(-1),
}}>
<Flex wrap="wrap" gap="small">
{mediaList.map((media, index) => (
<Image
key={index}
width={300}
height={300}
style={{ objectFit: 'cover' }}
src={media.srcUrl}
/>
))}
</Flex>
</Image.PreviewGroup>
</Space>
</List>
);
};

export default MediaUpload;
import { useState } from "react";
import { useList } from "@refinedev/core";
import axios from "axios";
import { List, Space, Upload, Image, Flex } from "antd";

const MediaUpload = () => {
const { data, refetch } = useList<IMedia>({
resource: "media",
});
const [mediaList, setMediaList] = useState(data?.data || []);
const url = useApiUrl();

const onUpload = async (options: any) => {
const { onSuccess, onError, file } = options;

const fmData = new FormData();
fmData.append("uploadedFile", file);
try {
const res = await axios.post(
`${url}/media/upload`,
fmData,
{
headers: { "content-type": "multipart/form-data" },
withCredentials: true
}
);

onSuccess("Ok");
const newMedia = res.data; // Assuming the response contains the new media item
setMediaList((prevList) => [...prevList, newMedia]); // Update the state with the new media item
} catch (err) {
onError({ err });
}
};
return (
<List>
<Space direction="vertical" size={50} style={{ width: "100%" }}>
<Upload.Dragger
name="file"
customRequest={onUpload}
listType="picture"
>
</Upload.Dragger>
<Image.PreviewGroup
preview={{
// Displays the image name
countRender: (current) => mediaList[current - 1].id.split("/").at(-1),
}}>
<Flex wrap="wrap" gap="small">
{mediaList.map((media, index) => (
<Image
key={index}
width={300}
height={300}
style={{ objectFit: 'cover' }}
src={media.srcUrl}
/>
))}
</Flex>
</Image.PreviewGroup>
</Space>
</List>
);
};

export default MediaUpload;
In this code, we use the useState hook to manage the state of the media list. When a new media item is uploaded successfully, we update the state with the new media item instead of refetching all media items. This approach is more efficient and ensures that the newly uploaded image is displayed immediately. For more information on managing state in React, you can refer to the React documentation on hooks (https://reactjs.org/docs/hooks-state.html). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai5mo ago
<@490961337896402944> kapa.ai is still learning and improving, please let us know how it did by reacting below