JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script>
</head>
<body>
<script>
// Initialize Firebase
var config = {
apiKey: "專案API金鑰號碼",
authDomain: "專案驗證網址",
databaseURL: "https://專案資料庫網址",
storageBucket: "",
};
firebase.initializeApp(config);
// Basic Write Operations
var fb = firebase.database().ref('aSetofRecords');
// 迴圈執行incId()十次寫入10筆資料
for (var i=0 ; i<10 ; i++) incId();
// creates a new, incremental record
// 參見 http://jsfiddle.net/firebase/xLq7grcc/
// 參見 https://gist.github.com/katowulf/6158392
function incId() {
// When working with data that could be corrupted by concurrent modifications,
// such as incremental counters, you can use a transaction() operation to update.
// The update function takes the current state of the data as an argument
// and returns the new desired state you would like to write.
// If another client writes to the location before your new value is successfully written,
// your update function is called again with the new current value, and the write is retried.
// This repeats until the transaction is accepted or you abort the transaction.
// 參見 https://firebase.google.com/docs/database/web/save-data#save_data_as_transactions
// 參見 https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction
fb.child('counter').transaction(function(currentValue) {
// Increment counter by 1, or set to 1 if it was undefined before.
return (currentValue||0) + 1
}, function(error, committed, currentData) { // an optional completion callback function
// 參見 https://firebase.google.com/docs/reference/android/com/google/firebase/database/Transaction.Handler#public-methods
if ( error ) // error: null if no errors occurred, otherwise it contains a description of the error
{
setError(error);
}
else if( committed ) // committed: True if the transaction successfully completed, false if it was aborted or...