EmbedModal: react-query, add useEmbed

This commit is contained in:
Alex Gleason 2022-08-21 12:37:14 -04:00
parent 0dd0742752
commit 491c0e9152
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7
2 changed files with 38 additions and 22 deletions

View file

@ -1,18 +1,9 @@
import React, { useState, useEffect } from 'react';
import React, { useEffect } from 'react';
import { FormattedMessage } from 'react-intl';
import api from 'soapbox/api';
import SafeEmbed from 'soapbox/components/safe-embed';
import { Modal, Stack, Text, Input } from 'soapbox/components/ui';
import { useAppDispatch } from 'soapbox/hooks';
import type { RootState } from 'soapbox/store';
const fetchEmbed = (url: string) => {
return (dispatch: any, getState: () => RootState) => {
return api(getState).get('/api/oembed', { params: { url } });
};
};
import useEmbed from 'soapbox/queries/embed';
interface IEmbedModal {
url: string,
@ -20,18 +11,13 @@ interface IEmbedModal {
}
const EmbedModal: React.FC<IEmbedModal> = ({ url, onError }) => {
const dispatch = useAppDispatch();
const [html, setHtml] = useState('');
const { data: embed, error, isError } = useEmbed(url);
useEffect(() => {
dispatch(fetchEmbed(url)).then(({ data }) => {
if (data?.html) {
setHtml(data.html);
}
}).catch(error => {
if (error && isError) {
onError(error);
});
}, []);
}
}, [isError]);
const handleInputClick: React.MouseEventHandler<HTMLInputElement> = (e) => {
e.currentTarget.select();
@ -48,7 +34,7 @@ const EmbedModal: React.FC<IEmbedModal> = ({ url, onError }) => {
<Input
type='text'
readOnly
value={html}
value={embed?.html || ''}
onClick={handleInputClick}
/>
</Stack>
@ -57,7 +43,7 @@ const EmbedModal: React.FC<IEmbedModal> = ({ url, onError }) => {
className='inline-flex rounded-xl overflow-hidden max-w-full'
sandbox='allow-same-origin'
title='embedded-status'
html={html}
html={embed?.html}
/>
</Stack>
</Modal>

View file

@ -0,0 +1,30 @@
import { useQuery } from '@tanstack/react-query';
import { useApi } from 'soapbox/hooks';
type Embed = {
type: string,
version: string,
author_name: string,
author_url: string,
provider_name: string,
provider_url: string,
cache_age: number,
html: string,
width: number,
height: number,
}
/** Fetch OEmbed information for a status by its URL. */
// https://github.com/mastodon/mastodon/blob/main/app/controllers/api/oembed_controller.rb
// https://github.com/mastodon/mastodon/blob/main/app/serializers/oembed_serializer.rb
export default function useEmbed(url: string) {
const api = useApi();
const getEmbed = async() => {
const { data } = await api.get('/api/oembed', { params: { url } });
return data;
};
return useQuery<Embed>(['embed', url], getEmbed);
}