How can we send/flash notitication/alert in a functional way in React ? Need to have a common function which can be used everywhere

Viewed 73

I want to have a notification or alert function where the messages to pop up and dissapear in sometime. I would like to know if there is a some library or implementation which provides a functional way to send notifications.

Requirement is to have a function which can be fired from redux actions or in service api callback, from functional/class components which aren't connected to redux.

Usecase 1

//I am looking for something like sendAlert from my imaginary library
import axios from 'axios';
import {sendAlert} from "imaginary-react-library";

function getData(url) {
axios.get(url).then(resp => {
    console.log(resp.data);
    sendAlert("API fired successfully")
});

}

Usecase 2

//I am looking for something like sendAlert from my imaginary library
import React from "react";
import {sendAlert} from "imaginary-react-code";

const Demo= () => {
return (<div onClick={() => sendAlert("Nice click")}>Demo Test</div>)
}

I have considered the below cases.

If we use hooks based implementation it has to be a functional component, I will not be able to use it in redux actions or in other functions

If I store some messages in redux state and use dispatch to update, I will be able to use it in actions and react-redux connected components but not in other places

Context will also have similar issues as Redux

1 Answers

You can check something like react-universal-flash. I think it covers your use cases. One of your use case is given in the read me and it will work same way in you service call use case as well. I have posted the sample from their readme.

import {flash} from "react-universal-flash";

const Layout = () => {
  return (
    <>
      <div onClick={() => flash("Haha",6000)}>Click for Hello</div>
      <div onClick={() => flash("Hi",6000,"success")}>Click for Hi</div>
    </>
  );
};

https://www.npmjs.com/package/react-universal-flash

Related