Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

reactjs - Is this the correct way to change a Firestore document with a button next to it?

This is a portion of the code to a react.js chat app. 'Lumens' are upvotes. Every message generates a new document which is sorted by its createdAt time. This all works.

I am attempting to print a button next to each 'message' document that adds 1 to its 'lumen' field. This code is no longer giving me errors- except the entire app fails to load. What am I doing wrong? I will post the rest of my code if desired.

function giveLumen(p){
  const db = firebase.firestore;
  const messages = db.collection('messages').doc(this)
  messages.update({lumens: 100})
}

function ChatMessage(props) {
  const { text, uid, photoURL, lumens } = props.message;

  const messageClass = uid === auth.currentUser.uid ? 'sent' : 'received';
  
  return (<>
    <div className={`message ${messageClass}`}>
      <img src={photoURL || 'https://api.adorable.io/avatars/23/[email protected]'} />

      
      <div className = "lumens">

        <button onClick= {giveLumen()} className="lumens">
        ??
        </button>

      </div>

      <p>{lumens}</p>
      <p>{text}</p>

    </div>
  </>)
}

Thanks for any help.

question from:https://stackoverflow.com/questions/65599877/is-this-the-correct-way-to-change-a-firestore-document-with-a-button-next-to-it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you're passing giveLumen() with parenthesis you're calling the function

<button onClick= {giveLumen()} className="lumens">

In the first time, I think you should remove them. So that you'll pass the reference to you're function

<button onClick= {giveLumen} className="lumens">

// You can also write it as following (almost the same)

<button onClick= {() => giveLumen()} className="lumens">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...