Next.js Discord

Discord Forum

No Real time data

Answered
Russian Blue posted this in #help-forum
Open in Discord
Russian BlueOP
I have 2 pages, create task and view tasks, if I create a task, and then go to the tasks page, it doesn't show automatically, I have to refresh to get the recent data from the database
Answered by Ray
if (data?.success) {
  form.reset();
  setSuccess(data.success);
  router.refresh()
}

try router.refresh() after create success
View full answer

45 Replies

Russian BlueOP
@DirtyCajunRice | AppDir Hey you still available?
@Russian Blue <@184479429404262410> Hey you still available?
paste the contents of those 2 pages
Russian BlueOP
tasks: import { currentUser } from "@/lib/auth"; import { getTasks } from "@/services/taskServices"; import TaskCard from "./_components/TaskCard"; import { Task } from "@prisma/client"; const TasksPage = async () => { const user = await currentUser(); if (!user || !user.id) return null; const userTasks = await getTasks(user?.id); return ( <div className="w-full h-full grid grid-cols-4 grid-rows-3 gap-4 p-4"> {userTasks.map((task: Task) => ( <TaskCard key={task.id} task={task} /> ))} </div> ); }; export default TasksPage;
3 backticks instead of 1
so the whole shebang gets code blocked
```ts
``\`
welp
giess i didnt need the backslashes lol
Russian BlueOP
createTask:
"use client";

const NewTaskForm = () => {
  const [error, setError] = useState<string | undefined>();
  const [success, setSuccess] = useState<string | undefined>();
  const [isPending, startTransition] = useTransition();
  const form = useForm<z.infer<typeof TaskSchema>>({
    resolver: zodResolver(TaskSchema),
    defaultValues: {
      title: "",
      description: "",
    },
  });
  // TODO: continue the action for createTask
  const onSubmit = (values: z.infer<typeof TaskSchema>) => {
    setError("");
    setSuccess("");
    startTransition(() => {
      createTask(values)
        .then((data) => {
          if (data?.error) {
            form.reset();
            setError(data.error);
          }
          if (data?.success) {
            form.reset();
            setSuccess(data.success);
          }
        })
        .catch(() => setError("Something went wrong!"));
    });
  };
  return (

    
      <Form {...form}>
        <form
          action=""
          onSubmit={form.handleSubmit(onSubmit)}
          className="flex flex-col "
        >
          <FormField
            control={form.control}
            name="title"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Title</FormLabel>
                <FormControl>
                  <Input
                    {...field}
                    disabled={isPending}
                    placeholder="Wash the dishes"
            
       
            control={form.control}
            name="description"
            render={({ field }) => (
            
              Description</FormLabel>
          
                  <Input
                    {...field}
                    disabled={isPending}
                    placeholder="3 plates, 4 spoons, and 5 mugs!"
                  />
                </FormControl>
     
          />
          but
            type="submit"
            disabled={isPending}
      
            Create Task
        
had to remove some stuff I dfont have discord nitor
ntiro
here is the tasks code:
import { currentUser } from "@/lib/auth";
import { getTasks } from "@/services/taskServices";
import TaskCard from "./_components/TaskCard";
import { Task } from "@prisma/client";

const TasksPage = async () => {
  const user = await currentUser();
  if (!user || !user.id) return null;
  const userTasks = await getTasks(user?.id);

  return (
    <div className="w-full h-full grid grid-cols-4 grid-rows-3 gap-4 p-4">
      {userTasks.map((task: Task) => (
        <TaskCard key={task.id} task={task} />
      ))}
    </div>
  );
};

export default TasksPage;
Task Card :
import { Task } from "@prisma/client";

const TaskCard = ({ task }: { task: Task }) => {
  return (
    <div className="bg-gray-100 rounded-md p-3 w-[200px] h-[100px]">
      <h1 className="text-xl">{task.title}</h1>
      <h6>{task.description}</h6>
      <p className="text-gray-500">{task.createdAt.toDateString()}</p>
    </div>
  );
};

export default TaskCard;
so in your create task
on success
how are you getting back to the other tab
is it not automatic?
Russian BlueOP
No i dont want it to be
ah. i see
Russian BlueOP
maybe several tasks need to be added consecutivbely
there may be a simple fix
whats your nav look like
Russian BlueOP
pasted like this since more than allowed characters
on your tasks button
27
try making it an <a> instead of a Link
if it works ill explain why
Russian BlueOP
yep works
not anymore tho, only worked once
if i refresh, works again for 1 hit only
Russian BlueOP
not working anymore tho, even if i refreshed xdd
@Russian Blue not working anymore tho, even if i refreshed xdd
if (data?.success) {
  form.reset();
  setSuccess(data.success);
  router.refresh()
}

try router.refresh() after create success
Answer
Russian BlueOP
I guess it's working now, why tho>
because of router cache
if you use server action, you could invalidate the router cache by using revalidatePath()
Russian BlueOP
yep, I thought it was related to the caching, thanks guys!
Do you think I would need something for state management to save up on db calls I am doing, or is it fine?
@Ray router cache is already doing this for you<:lolsob:753870958489632819>
Russian BlueOP
yeah haha but I mean, if I have caching enabled, and I add a new task, it won't show until the time has passed, if I manage states, then when I create a task, I can change the state of tasks in the app to oldState + new Task
something like this would be efficient in nextjs or bottleneck?
Russian BlueOP
Alright, sounds good, thanks!!