swr icon indicating copy to clipboard operation
swr copied to clipboard

Passing an immer produce curry into bound mutate sometimes results in an undefined object

Open varunsrin opened this issue 2 years ago • 1 comments

Bug report

Using bound mutate with immer's produce sporadically returns an undefined item for produce to mutate, which causes a failure.

Version: swr 0.5.6

Observed Behavior The object that produce operates on ends up being undefined in some cases. This is not consistent, but we've seen errors logs from users that occur roughly 1% of the time when the bound mutate is triggered.

Expected Behavior Since the EditButton component is only rendered when data is available, I would assume that mutate never returns a undefined object.

This is easy to workaround by adding a null check around the operation on profile, but I wanted to see if this was expected behavior or a bug.

export default function Profile(): JSX.Element {
  const { data, error, mutate } = useSWR<IProfile>(basePath);
  if (!data) {
    return <BlankProfile profileAddress={profileAddress} />;
  }
  return (<EditButton mutateProfle={mutate} />) 
 }
 
 
interface EditButtonProps {
  targetAddress: string;
  followState: FollowState;
  mutateProfile?: (data?: any, shouldRevalidate?: boolean) => Promise<any | undefined>;
}
 
export function EditButton(props: EditButtonProps): JSX.Element {
 
  const onClick = async (): Promise<void> {  
    if (mutateProfile) {
      mutateProfile(
        produce((profile: IProfile) => {
           // This fails because profile is sometimes undefined
           profile.editCount += 1;
        }),
        false
      );
    }
    // Make API Call
     if (mutateProfile) {
       mutateProfile();
     }   
   }

 }

varunsrin avatar Aug 05 '21 20:08 varunsrin

Thanks for reporting! We haven’t got similar reports about this yet, will keep this open for now.

shuding avatar Aug 08 '21 15:08 shuding