#*I sense something terribly cursed here*

1 messages · Page 1 of 1 (latest)

tranquil hamlet
#
export default async function SendFriendRequestButton({ targetUser }: { targetUser: string }) {
  const currentUser = await getCurrentUser();
  const alreadyFriends = currentUser?.relationships?.friends?.some(friend => friend.id === targetUser);
  const alreadySentRequest = currentUser?.relationships?.outboundFriendRequests?.some(friend => friend.id === targetUser);
  const hasInboundRequest = currentUser?.relationships?.inboundFriendRequests?.some(friend => friend.id === targetUser);

  return (
    <form>
      <Toaster />
      <InternalButton targetUser={targetUser} alreadyFriends={!!alreadyFriends} alreadySentRequest={!!alreadySentRequest} hasInboundRequest={!!hasInboundRequest} />
    </form>
  )
}```

```export default function InternalButton({ targetUser, alreadyFriends, alreadySentRequest, hasInboundRequest }: { targetUser: string, alreadyFriends: boolean, alreadySentRequest: boolean, hasInboundRequest: boolean }) {
  let action: any
  if (alreadyFriends) {
    action = unfriendActi
on;
  } else if (alreadySentRequest) {
    action = unsendFriendRequestAction;
  } else if (hasInboundRequest) {
    action = acceptFriendRequestAction;
  } else {
    action = sendFriendRequestAction;
  }

  const { pending } = useFormStatus();
  const [state, formAction] = useFormState(action, undefined)

  // TODO: allow retries and more descriptive errors
  useEffect(() => {
    if (state === 'error') {
      toast.error("Error changing friend status!")
    }
  }, [state])

  return (
    <>
      <input type="hidden" name="targetUser" value={targetUser} readOnly />
      <button
        aria-disabled={pending}
        formAction={formAction}
        className={`my-4 ${alreadyFriends || alreadySentRequest ? 'bg-gray-500 hover:bg-gray-400' : 'bg-blue-500 hover:bg-blue-400'} text-white p-2 rounded `}
      >
        {pending && <LoadingSpinner />}

        {alreadyFriends && 'Remove Friend'}
        {alreadySentRequest && 'Unsend Friend Request'}
        {hasInboundRequest && 'Accept Friend Request'}
        {(!alreadyFriends && !alreadySentRequest && !hasInboundRequest) && 'Send Friend Request'}
      </button>
    </>
  )
}```
#

Sorry I know we're now in code land (let me know if I should post a help form) but the form needs data in the server context. I guess I could move that one layer up and have the entire form be a client component?

#

It's just nice to have the buttons get their own data like this

sour lantern
#

you can't keep the form as server component and control its interactivity at the same time