从除了当前授权用户以外的任何人那里收到浏览器通知。

huangapple go评论72阅读模式
英文:

Getting a browser notification from anybody but the current auth. user

问题

// Chat.js中的代码

import { useEffect, useState } from "react";
import { addDoc, collection, serverTimestamp, onSnapshot, query, where, orderBy } from "firebase/firestore";
import { auth, db } from "../firebase-config";
import "../styles/Chat.css";
import IDLogo from "../images/IDLogo.png";
import notificationSound from "../sounds/message_sound.mp3";
import addNotification from "react-push-notification";
import DefaultProfilePicture from "../images/default_pfp.jpeg";

export const Chat = props => {
  const { room } = props;
  const [newMessage, setNewMessage] = useState();
  const [messages, setMessages] = useState([]);

  const messagesRef = collection(db, "messages");

  useEffect(() => {
    const queryMessages = query(messagesRef, where("room", "==", room), orderBy("createdAt"));
    const unsubscribe = onSnapshot(queryMessages, snapshot => {
      let messages = [];
      snapshot.forEach(doc => {
        messages.push({ ...doc.data(), id: doc.id });
      });
      setMessages(messages);
    });

    return () => unsubscribe();
  }, []);

  useEffect(() => {
    const messagesContainer = messagesRef.current;
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }, [messagesRef]);

  const handleSubmit = async e => {
    e.preventDefault();
    if (newMessage === "") return;

    const currentUser = auth.currentUser;

    await addDoc(messagesRef, {
      text: newMessage,
      createdAt: serverTimestamp(),
      user: currentUser.displayName,
      profilePicture: currentUser.photoURL,
      room,
    });

    if (newMessage && newMessage.user !== auth.currentUser.displayName) {
      addNotification({
        title: "New Message",
        message: newMessage.text,
        duration: 5000,
        native: true,
        icon: IDLogo,
      });
    }

    setNewMessage("");
  };

  useEffect(() => {
    const audio = new Audio(notificationSound);
    const lastMessage = messages[messages.length - 1];

    if (lastMessage && lastMessage.user !== auth.currentUser.displayName) {
      audio.play();
    }
  }, [messages]);

  return (
    <div className='chat'>
      <div className='header'>
        <h1>
          Welcome to: <span className='Chat__room--title'>{room.toUpperCase()}</span>
        </h1>
      </div>

      <div ref={messagesRef} className='messages'>
        {messages.map(message => (
          <p className='Chat__message'>
            {message.profilePicture ? (
              <img className='profile__picture' referrerpolicy='no-referrer' src={message.profilePicture} alt={message.user} />
            ) : (
              <img className='profile__picture' src={DefaultProfilePicture} alt={message.user}></img>
            )}
            {message.user} : {message.text}
          </p>
        ))}
      </div>
      <div className='send__message__container'>
        <form onSubmit={handleSubmit} className='new__message__form'>
          <input
            spellCheck='false'
            onChange={e => setNewMessage(e.target.value)}
            className='new__message__input'
            placeholder='Type a message here...'
            value={newMessage}
          />
          <button type='submit' className='signOut--sendMessage__button'>
            Send
          </button>
        </form>
      </div>
    </div>
  );
};
英文:

I'm currently building a chat app in React JS and I've been going crazy for the past two days with this issue. I want to make it so whenever there is a new message, a browser notification appears.

The issue is that I only get a notification when I send a message, not when anybody else sends a message. It's supposed to be literally the other way around.

I'm using the react-push-notification npm package to implement this.

Chat.js:

import { useEffect, useState } from &quot;react&quot;;
import { addDoc, collection, serverTimestamp, onSnapshot, query, where, orderBy } from &quot;firebase/firestore&quot;;
import { auth, db } from &quot;../firebase-config&quot;;
import &quot;../styles/Chat.css&quot;;
import IDLogo from &quot;../images/IDLogo.png&quot;;
import notificationSound from &quot;../sounds/message_sound.mp3&quot;;
import addNotification from &quot;react-push-notification&quot;;
import DefaultProfilePicture from &quot;../images/default_pfp.jpeg&quot;;
export const Chat = props =&gt; {
const { room } = props;
const [newMessage, setNewMessage] = useState();
const [messages, setMessages] = useState([]);
const messagesRef = collection(db, &quot;messages&quot;);
useEffect(() =&gt; {
const queryMessages = query(messagesRef, where(&quot;room&quot;, &quot;==&quot;, room), orderBy(&quot;createdAt&quot;));
const unsubscribe = onSnapshot(queryMessages, snapshot =&gt; {
let messages = [];
snapshot.forEach(doc =&gt; {
messages.push({ ...doc.data(), id: doc.id });
});
setMessages(messages);
});
return () =&gt; unsubscribe();
}, []);
useEffect(() =&gt; {
const messagesContainer = messagesRef.current;
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}, [messagesRef]);
const handleSubmit = async e =&gt; {
e.preventDefault();
if (newMessage === &quot;&quot;) return;
const currentUser = auth.currentUser;
await addDoc(messagesRef, {
text: newMessage,
createdAt: serverTimestamp(),
user: currentUser.displayName,
profilePicture: currentUser.photoURL,
room,
});
if (newMessage &amp;&amp; newMessage.user !== auth.currentUser.displayName) {
addNotification({
title: &quot;New Message&quot;,
message: newMessage.text,
duration: 5000,
native: true,
icon: IDLogo,
});
}
setNewMessage(&quot;&quot;);
};
useEffect(() =&gt; {
const audio = new Audio(notificationSound);
const lastMessage = messages[messages.length - 1];
if (lastMessage &amp;&amp; lastMessage.user !== auth.currentUser.displayName) {
audio.play();
}
}, [messages]);
return (
&lt;div className=&#39;chat&#39;&gt;
&lt;div className=&#39;header&#39;&gt;
&lt;h1&gt;
Welcome to: &lt;span className=&#39;Chat__room--title&#39;&gt;{room.toUpperCase()}&lt;/span&gt;
&lt;/h1&gt;
&lt;/div&gt;
&lt;div ref={messagesRef} className=&#39;messages&#39;&gt;
{messages.map(message =&gt; (
&lt;p className=&#39;Chat__message&#39;&gt;
{message.profilePicture ? (
&lt;img className=&#39;profile__picture&#39; referrerpolicy=&#39;no-referrer&#39; src={message.profilePicture} alt={message.user} /&gt;
) : (
&lt;img className=&#39;profile__picture&#39; src={DefaultProfilePicture} alt={message.user}&gt;&lt;/img&gt;
)}
{message.user} : {message.text}
&lt;/p&gt;
))}
&lt;/div&gt;
&lt;div className=&#39;send__message__container&#39;&gt;
&lt;form onSubmit={handleSubmit} className=&#39;new__message__form&#39;&gt;
&lt;input
spellCheck=&#39;false&#39;
onChange={e =&gt; setNewMessage(e.target.value)}
className=&#39;new__message__input&#39;
placeholder=&#39;Type a message here...&#39;
value={newMessage}
/&gt;
&lt;button type=&#39;submit&#39; className=&#39;signOut--sendMessage__button&#39;&gt;
Send
&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
);
};

答案1

得分: 1

Just move your add notification function out of handle submit function :

如果 (newMessage && newMessage.user !== auth.currentUser.displayName) {
添加通知({
标题: "新消息",
消息: newMessage.text,
持续时间: 5000,
原生: true,
图标: IDLogo,
});
}

Take it to the next useEffect :

将其移到下一个 useEffect 中:

useEffect(() => {
const audio = new Audio(notificationSound);
const lastMessage = messages[messages.length - 1];

if (lastMessage && lastMessage.user !== auth.currentUser.displayName) {
audio.play();
添加通知({
标题: "新消息",
消息: newMessage.text,
持续时间: 5000,
原生: true,
图标: IDLogo,
});
}
}, [messages]);

英文:

Just move your add notification function out of handle submit function :

if (newMessage &amp;&amp; newMessage.user !== auth.currentUser.displayName) {
addNotification({
title: &quot;New Message&quot;,
message: newMessage.text,
duration: 5000,
native: true,
icon: IDLogo,
});
}

Take it to the next useEffect :

useEffect(() =&gt; {
const audio = new Audio(notificationSound);
const lastMessage = messages[messages.length - 1];
if (lastMessage &amp;&amp; lastMessage.user !== auth.currentUser.displayName) {
audio.play();
addNotification({
title: &quot;New Message&quot;,
message: newMessage.text,
duration: 5000,
native: true,
icon: IDLogo,
});
}}, [messages]);

huangapple
  • 本文由 发表于 2023年4月20日 08:56:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76059819.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定