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 ?
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,
This should solve your issue and not sure why you're reassigning to
mySnack
, you could callSnackBar(' ')
directly.Also, for best practices, name files that contain React components with the extension
tsx
.