#NextJS OptimisticHook

1 messages · Page 1 of 1 (latest)

umbral idol
#

iam really in trouble with this hook iam kinda new i searched watched lot of videos on youtube also visit most of the blog site but didnt found the solution
here is the code

    id : string;
    created_at? : FieldValue;
    data : LinkItemScheme[] | [];
}```

`const [sections, setSections] = useState<SectionScheme[]>(STATIC_SECTION_DATA);
    const [optimisticSections, updateOptimisticSections] = useOptimistic<SectionScheme[], SectionScheme>(
        sections,
        (currentState, updatedSection) => {
            return [...currentState, updatedSection];
        }
    );
     const CreateSection = async (section : SectionScheme) => {
        const regex = /[-\/()[\];+\-^*]/;
        
        if(section.id.length > 3) {
            const newSection: SectionScheme = { ...section };
            updateOptimisticSections(newSection);
        }
        else {
            alert('Please Enter Section Name With Least 3 Character Long');
        }
        console.log('Creating new section in db... ', regex.test(section.id));
    }`

the problem here is when the CreateSection function get called the updateOptimisticSections create the new section for blink of an eye then revert back
raw flumeBOT
#

Hi @umbral idol. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the knowledge sources provided, it seems like you're experiencing a common issue with the useOptimistic hook in Next.js. This issue is also discussed in a Github issue (https://github.com/vercel/next.js/issues/49619) where the optimistic value is shown during the server action, but the previous value is rendered before the revalidated data is rendered, causing a flash of the previous value.

One user in the Github issue thread suggested using a custom hook to achieve the same functionality as useOptimistic. Here's the code they provided:

function useOptimistic<T>(passthrough: T) {
  const [value, setValue] = useState<T>(passthrough);

  useEffect(() => {
    setValue(passthrough);
  }, [passthrough]);

  return [value, setValue] as const;
}

This custom hook might not cover all use cases, but it has been working for them. You could try to replace useOptimistic with this custom hook and see if it solves your problem.

Another user suggested using useTransition from React along with useOptimistic. Here's the code they provided:

"use client";

import { togglePositionActive } from "@/api/position";
import { Switch } from "@mui/material";
import { useOptimistic, useTransition, startTransition } from "react";

function ActiveSwitch({ isActive }: ActiveSwitchProps) {
  // ADD THIS
  const [_, startTransition] = useTransition();

  const [optimisticIsActive, setOptimisticIsActive] = useOptimistic(
    isActive,
    (_, newValue: boolean) => newValue,
  );
  // rest of the code
}

You could try to use useTransition along with useOptimistic and see if it solves your problem.

#

Please note that these are suggestions based on the knowledge sources provided and might not solve your problem. If the problem persists, I would recommend opening a new issue in the Next.js Github repository.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: