How to use react hook as common component with typescript

1k Views Asked by At

I have a SnackBar.ts file as below

import { useSnackbar } from 'notistack';

const SnackBar = (message:string, isError?:boolean) => {
  const { enqueueSnackbar } = useSnackbar();
  return enqueueSnackbar(message, {
    anchorOrigin: {
      horizontal: 'right',
      vertical: 'top'
    },
    variant: isError ? 'error' : 'success',
    style: { whiteSpace: 'pre-line' }
  });
};

export default SnackBar;

So I started use that in my compoonent tsx like below

    import { FC, useEffect, useState } from 'react';
    import { SnackBar } from '../../snackbar';

    const userEditForm: FC = (props) => {
    const mySnack = SnackBar;
    
    useEffect(() => {
        console.log('error');
        if (!loading && submitForm) {
          if (!error) {
            mySnack('user updated');
          } else {
            mySnack(error, true);
          }
        }
      }, [error, loading, submitForm]);
       
     return ( <MyComponent /> );
}

I'm getting this error "Error: Invalid hook call. Hooks can only be called inside of the body of a function component"

Error is coming from this line mySnack('user updated');

All I wanted to do is use that enqueueSnackbar as a shared method. How can I do that in typescript ?

1

There are 1 best solutions below

9
On

The error is exactly what it says. According to the snippet, you're trying to call useEffect() outside of a function just below the import that is the error.

try this,

import { SnackBar } from '../../snackbar';


const SomeComponent = () => {

const mySnack = SnackBar;

callSnack(){
console.log('error');
    if (!loading && submitForm) {
      if (!error) {
        mySnack('user updated');
      } else {
        mySnack(error, true);
      }
    }
}


useEffect(() => {
    callSnack();
  }, [error, loading, submitForm]);

return <div> Somehting </div>;
}

This should solve your issue and not sure why you're reassigning to mySnack, you could call SnackBar(' ') directly.

Also, for best practices, name files that contain React components with the extension tsx.