How to play a sound when a new order is placed using ReactJS

Viewed 162

I am building this PWA with ReactJS.

As the title says, I just want to play a sound whenever a new order is placed.

I am using the Context API in order to manage the states.

This is my OrderContext.js where I fetch the orders from the API using React Query.

import React, { createContext } from "react";
import { useQuery } from "react-query";
import apiClient from "../EventService";

export const OrderContext = createContext();

export const OrderProvider = (props) => {
  const fetchOrders = async () => {
    const { data } = await apiClient.getEvents();
    return data;
  };

  let { data: orders, status } = useQuery("orders", fetchOrders, {
    refetchInterval: 15000,
    refetchIntervalInBackground: true,
    notifyOnStatusChange: false,
  });

  return (
    <OrderContext.Provider value={[orders, status]}>
      {props.children}
    </OrderContext.Provider>
  );
};

Then somewhere in my OrdersList.js component, I just use the state and map through it:

{orders.map((order) => (
     <Order key={order.id} order={order} />
))}

And lastly, in my Order.js component is where I check if there is a new order or not:

I am using this function to check if the order has been placed 15 or less minutes ago.

const isNewOrder = (orderCreatedDate) => {
    if (moment().diff(moment(orderCreatedDate)) / 900000 <= 1) {
      return true;
    } else {
      return false;
    }
  };

and then in the in the JSX of the component I simply do this to display a badge on the new orders:

  {isNewOrder(order.date_created) && (
        <Badge style={{ padding: 3 }} content="Nuevo" />
   )}

I am having troubles adding a sound effect to these new orders, I tried using Howler but couldn't make it work properly.

If someone could help me or maybe show me a way to achieve this I would really appreciate. I can provide the full components if needed, let me know. Thanks in advance.

Have a nice day!

1 Answers

I think your best approach is to add a prop to your Order component and check if you are on the order list page or on the order page. If on one single order then you call sound.play, otherwise you do not.

Also, you should use React Howler if you're not already. Regular Howler does not play well (no pun intended) with React.

Finally, you should add a componentWillUnmount function to stop the sound from playing (just call sound.stop() inside componentWillUnmount).

Related