Код: Выделить всё
// store.ts
import { create } from 'zustand';
export const useCounterStore = create((set) => ({
count: 0,
increment: () => set((s) => ({ count: s.count + 1 })),
setCount: (c: number) => set({ count: c }),
}));
// actions.ts
'use server';
export async function incrementServerCount(count: number) {
// simulate DB update
await new Promise((r) => setTimeout(r, 500));
return count + 1;
}
// page.tsx
'use client';
import { useTransition } from 'react';
import { incrementServerCount } from './actions';
import { useCounterStore } from './store';
export default function HomePage() {
const { count, setCount } = useCounterStore();
const [isPending, startTransition] = useTransition();
async function handleClick() {
startTransition(async () => {
const updated = await incrementServerCount(count);
setCount(updated);
});
}
return (
Count: {count}
{isPending ? 'Updating...' : 'Increment'}
);
}
Похоже, что переходы состояния Zustand и действий сервера не синхронизируются должным образом в режиме параллельного рендеринга React. Как я могу обеспечить согласованность состояния между действиями сервера Next.js и состоянием клиента Zustand при использовании useTransition()?
Подробнее здесь: https://stackoverflow.com/questions/798 ... te-updates
Мобильная версия