import { Form, FormRow, FormButtons, Flexbox, TextField, SubmitButton, Button, Toggle, } from 'react-basics'; import { useEffect, useMemo, useRef, useState } from 'react'; import { getRandomChars } from 'next-basics'; import { useRouter } from 'next/router'; import useApi from 'hooks/useApi'; import useMessages from 'hooks/useMessages'; const generateId = () => getRandomChars(16); export function ShareUrl({ websiteId, data, onSave }) { const { formatMessage, labels, messages } = useMessages(); const { name, shareId } = data; const [id, setId] = useState(shareId); const { post, useMutation } = useApi(); const { basePath } = useRouter(); const { mutate, error } = useMutation(({ shareId }) => post(`/websites/${websiteId}`, { shareId }), ); const ref = useRef(null); const url = useMemo( () => `${process.env.analyticsUrl || location.origin}${basePath}/share/${id}/${encodeURIComponent( name, )}`, [id, name], ); const handleSubmit = async data => { mutate(data, { onSuccess: async () => { onSave(data); ref.current.reset(data); }, }); }; const handleGenerate = () => { const id = generateId(); ref.current.setValue('shareId', id, { shouldValidate: true, shouldDirty: true, }); setId(id); }; const handleCheck = checked => { const data = { shareId: checked ? generateId() : null }; mutate(data, { onSuccess: async () => { onSave(data); }, }); setId(data.shareId); }; useEffect(() => { if (id && id !== shareId) { ref.current.setValue('shareId', id); } }, [id, shareId]); return ( <> {formatMessage(labels.enableShareUrl)} {id && (

{formatMessage(messages.shareUrl)}

{formatMessage(labels.save)}
)} ); } export default ShareUrl;