pmndrs / zustand

🐻 Bear necessities for state management in React

Home Page:https://zustand-demo.pmnd.rs/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Re-render issue while performing open and setOpen using shadcn

Akshaypmna18 opened this issue · comments

Discussed in #2354

I'm sorry this was resolved or closed by @dbritto-dev before solving the actual problem

Originally posted by Akshaypmna18 February 22, 2024
https://stackoverflow.com/questions/77826561/shadcn-reusuable-dialog-component-called-twice-renders-update-form-only

I have implemented a reusable dialog component using Shadcn in my todo app. However, I'm encountering an issue where the component is not working as needed. The add form and update form opens only after clicking twice. And when we click the pencil icon immediately after adding a todo it will pop add form instead of update form. I'm using zustand for state management.

Dialog Component

export default function DialogModal({ children, id, text }) {
  const { handleTodo, todo, setTodo, isOpen, setIsOpen } = useTodo(
    (state) => state
  );
  return (
    <Dialog open={isOpen} onOpenChange={() => setIsOpen()}>
      <DialogTrigger>{children}</DialogTrigger>
      <DialogContent className="max-w-[400px]">
        <DialogHeader>
          <DialogTitle className="bold text-[calc(1.25rem+.5vw)]">
            <big>{id ? "Update Task" : "Add Task"}</big>
          </DialogTitle>
        </DialogHeader>
        <Input
          className="font-[poppins]"
          placeholder="Enter the task..."
          defaultValue={text}
          onChange={(e) => setTodo(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter") handleTodo(todo.trim(), id);
          }}
        />
        <DialogFooter>
          <Button
            className="text-[calc(1rem+.5vw)] mx-auto w-[min(90%,10rem)]"
            onClick={() => handleTodo(todo.trim(), id)}
          >
            {id ? "Update" : "Add"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

If I set 'setIsOpen(!isOpen)' the dialog component only shows the latest todo

update todo

     <DialogModal id={id} text={text}>
      <ToolTipComp Content={() => <ToolTipContent />}>
        <Pencil2Icon
          onClick={() => setIsOpen(true)}
          className="min-h-[1.5rem] min-w-[1.5rem] cursor-pointer hover:text-rose-500"
        />
      </ToolTipComp>
    </DialogModal>

add todo

    <DialogModal>
      <Button
        onClick={() => setIsOpen(true)}
        className="font-[poppins] fixed right-[calc(2.5rem+1vw)] bottom-[calc(3rem+1vh)] text-[calc(2rem+1vw)] rounded-full h-[calc(2.5rem+1vw)] w-[calc(2.5rem+1vw)]"
      >
        +
      </Button>
    </DialogModal>

demo

dialog component code

add todo code

update todo code

zustand store code

video for better understanding

Use devices with a width below 640 pixels or adjust it in the browser.

video after @dbritto-dev 's contribution

Let's reopen #2354.