I'm currently working on a React Application based on the MERN stack, and I have a use case where I would like to implement instant notifications within the application.
For example, I'm having a shopping cart, where the items in it are added to the localstorage
when the user "adds to the cart
" and fetched from the localstorage
and shown to the user when they need to view it. What I need to achieve is, displaying a badge (as shown in the image) containing the amount of items in the cart.
As per my research I have found that it is impossible to watch and trigger events related to localstorage within the same tab, which means that is not the ideal solution. I need to update the badge as soon as the user adds to the cart.
What will be my best options for this use case? Is there a convenient way to implement real time notifications in React?
(Note that this badge is on the header which is a separate component, and the 'add to cart
' is in another component.)
You can use either of these: functional component where you leverage on the useState Hook or use the class based component. In this example I am levering a package 'local-storage' to get the saved items in the local storage.
import React, {useState} from 'react';
import ls from 'local-storage';
const Cart = () => {
const [numberOfCart, setNumberOfCart] = useState(0);
setNumberOfCart(ls.get('cart').length);
return (
<div>
<span>{numberOfCart}</span>
</div>
)
}
class Cart extends React.Component {
constructor() {
super();
this.state = {
numberOfCart: 0
}
}
componentDidMount() {
this.setState({ numberOfCart: ls('get').length })
}
render() {
return (
<div>
<span>{this.state.numberOfCart}</span>
</div>
);
}
}