Rate my practice - File scoped variable
TL. DR. I'm setting a "let myVariable" on a file level scope to share it across my app. Are there some caveats on doing this?
I was looking for a way to use my alert notifications work from all around the app with just one line. I use to do this with Redux, but since my new theme came with react-notification-alert, which is a little bit rustic, it was going to need some special effort ( not actually a lot of effort, but lately I'm also wary of Redux ) to develop the Redux connection.
So, looking for a way to make it app-wide available I came with this technique, which I haven't seen around so I don't know if it may have some downsides I haven't thought about.
To explain it first I need to go through how is this library intended to be used. It's fairly simple:
You import the component, you place it in your app, get a reference to it with a ref and then you call a method on it to show the notification.
To use it from anywhere within my app I would need to be able to call the notify method from anywhere, so I created another file with some utility methods, which basically looks like this:
//Notifier.js
let component = null;
let initialQueue = [];
const options = { /*defaultOptions*/ }
export const setComponent = ( comp )=>{
component=comp;
for( let i=0; i<initialQueue.length; i++ )
component.notificationAlert( initialQueue[i] );
initialQueue = [];
};
export const notify = {
custom: ( options )=>{
if( !component )
initialQueue.push( options );
else
component.notificationAlert( options );
}
success: ( message )=>{
const opts = {
...options,
message,
type: 'success',
icon: "check-icon-class",
};
notify.custom( opts );
},
//error, info... and other utilities.
}
File explanation:
I import setComponent in the component where I get the ref to the NotificationAlert component, very high in the tree hierarchy.
Now, from anywhere in the project, I can import { notify } from Notifier.js and call notify.success('The message');
I could have used context to prevent setting a file level variable, but I can't use context ( or that I think ) outside of react components definitions, let's say my Api.js file which by default fires a notification on failed requests.
So, what do you guys think? Do you feel eyestrain by looking at this? Can you think of any caveats of this technique?
Cheers.