简体   繁体   中英

React's useTransition() stucked in isPending = true when calling api routes from /pages/api folder

I am having issue with useTransition() that it is being set to true but actually never changes back to false. I am trying to delete record from MongoDB and once it is finished I would like to refresh React Server Component as explained here: https://beta.nextjs.org/docs/data-fetching/mutating

Issue is that in this case server component won't get refreshed and Button is stucked with loading text.

'use client'

const DeleteButton = ({ details }) => {
  const [isPending, startTransition] = useTransition();
  const router = useRouter();
  
  const handleDelete = async () => {
    await fetch('/api/clients', { method: 'DELETE', body: details._id });
     startTransition(() => {
       console.log('tran started', isPending);
       router.refresh();
     });
  }

  useEffect(() => {
    // at load isPending = false
    // after start tranisition it is set to false
    // but it never returns back to false 
    console.log('is pending ? ', isPending);
  }, [isPending]);

  return <Button onClick={() => handleDelete()}>{ isPending ? 'Loading' : 'Delete' }</Button>
}

This is BE code at /api/clients

import type { NextApiRequest, NextApiResponse } from 'next';
import ClientsCollection from '../../db/collections/clients';
import Client from '../../helpers/interfaces/client';

type Data = {
  name: string;
};
const clientsCollection = new ClientsCollection();

export default function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  switch (req.method) {
    case 'DELETE': {
      const result = clientsCollection.deleteClientById(req.body);
      res.status(200).json(result);
    }
    default:
      res.status(403);
  }
}

Closing this.

If you are going to use react-redux or any other tool that recommends parent level Context together with useTransition() then you have to apply it only to Client components that are leaves otherwise transition will be blocked in isPending === true state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM