import { useEffect } from "react"; import type { NextPage } from "next"; import { useRouter } from "next/router"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faChevronLeft } from "@fortawesome/pro-regular-svg-icons"; import clsx from "clsx"; import { useForm } from "react-hook-form"; import { withPageOnboardingRequired } from "../../../lib/session-helpers"; import { findConversation } from "../../database/sms"; import type { Sms } from "../../database/_types"; import { SmsType } from "../../database/_types"; import supabase from "../../supabase/client"; import useUser from "../../hooks/use-user"; import useConversation from "../../hooks/use-conversation"; import Layout from "../../components/layout"; type Props = { recipient: string; conversation: Sms[]; } type Form = { content: string; } const Messages: NextPage = (props) => { const { userProfile } = useUser(); const router = useRouter(); const recipient = router.query.recipient as string; const { conversation, error, refetch, sendMessage } = useConversation({ initialData: props.conversation, recipient, }); const pageTitle = `Messages with ${recipient}`; const { register, handleSubmit, setValue, formState: { isSubmitting, }, } = useForm
(); const onSubmit = handleSubmit(async ({ content }) => { if (isSubmitting) { return; } sendMessage.mutate({ to: recipient, content, }); setValue("content", ""); }); useEffect(() => { if (!userProfile) { return; } const subscription = supabase .from(`sms:customerId=eq.${userProfile.id}`) .on("INSERT", (payload) => { const message = payload.new; if ([message.from, message.to].includes(recipient)) { refetch(); } }) .subscribe(); return () => void subscription.unsubscribe(); }, [userProfile, recipient, refetch]); if (!userProfile) { return ( Loading... ); } if (error) { console.error("error", error); return ( Oops, something unexpected happened. Please try reloading the page. ); } return (
Back
    {conversation!.map(message => { return (
  • {message.content}
  • ) })}
); }; export const getServerSideProps = withPageOnboardingRequired( async (context, user) => { const recipient = context.params?.recipient; if (!recipient || Array.isArray(recipient)) { return { redirect: { destination: "/messages", permanent: false, }, }; } const conversation = await findConversation(user.id, recipient); return { props: { recipient, conversation, }, }; }, ); export default Messages;