Next.js Discord

Discord Forum

How can I run a function in client component from another client component, when the parent is a RSC

Answered
Kawakawa posted this in #help-forum
Open in Discord
Original message was deleted.
Answered by Asian black bear
Usually you would gate the initial run by checking the state for undefinedness, or just a latch ref
View full answer

9 Replies

Kawakawa
Code for the filtering form:
export const FilterOptionsFormSchema = z
  .object({
    dateRange: z
      .object({
        from: z.number().optional(),
        to: z.number().optional(),
      })
      .optional(),
    ordering: z.enum(["asc", "desc"]).optional(),
    message: z.string().optional(),
    category: z.string().optional(),
  })
  .strict();

type FormSchema = z.infer<typeof FilterOptionsFormSchema>;

export default function FilteringForm({
  categories,
  serverId,
}: {
  categories: string[] | undefined;
  serverId: string;
}) {
  const [filters, setFilters] = useAtom(loggingFiltersAtom);
  const [selectedParticipants, setSelectedParticipants] = useAtom(selectedParticipantsAtom);

  const form = useForm<FormSchema>({
    resolver: zodResolver(FilterOptionsFormSchema),
  });

  const debouncedRequest = useDebounce(() => {
    console.log("Debounced Request Ran!", { ...form.getValues(), participants: selectedParticipants });

    const { dateRange, message, ordering, category } = form.getValues();

    const newFilters: GetLogs = {
      ...filters,
      message: message || undefined,
      participants: selectedParticipants?.length ? selectedParticipants.map((p) => p.id) : undefined,
      categories: category ? [category] : undefined,
      ordering: ordering || undefined,
      // Timestamps in the API are in seconds, not MS!
      startTimestamp: Math.floor((dateRange?.from || 0) / 1000),
      endTimestamp: Math.floor((dateRange?.to || endOfDay(new Date()).getTime()) / 1000),
    };

    if (JSON.stringify(newFilters) !== JSON.stringify(filters)) {
      setFilters(newFilters);
    }
  }, 500);

  const clearFilters = () => {
    // ...
  };

  // ? On selected participants change, submit filters. - NOT WORKING RIGHT NOW - SUBMITS ON PAGE LOAD (BAD)!
  useEffect(() => {
    debouncedRequest();
  }, [debouncedRequest, selectedParticipants]);

  return (
// ... render comp.
Kawakawa
-bump
@Kawakawa -bump
Asian black bear
It has nothing to do with jotai, useEffect ALWAYS runs once on mount, no matter what
Kawakawa
Yeah I actually know that, don't know why I didn't think of that lmao
Asian black bear
Usually you would gate the initial run by checking the state for undefinedness, or just a latch ref
Answer
Asian black bear
Also your atom has a default state
Also also useHydrateAtoms
Kawakawa
Yeah alright, understood.
Thanks.