Last active
March 26, 2022 20:51
-
-
Save JakeCoxon/cbc7f7909826ab3db833b40931ce088d to your computer and use it in GitHub Desktop.
Firebase Mobx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import _ from 'https://npmcdn.com/lodash@4.15.0' | |
import 'https://npmcdn.com/firebase@3.3.0/firebase.js' | |
var config = { | |
apiKey: "AIzaSyCNV9EVtgHpNCHJoRe8xwkCRIpKZ3IFI_M", | |
authDomain: "example-app-ccfdb.firebaseapp.com", | |
databaseURL: "https://example-app-ccfdb.firebaseio.com", | |
storageBucket: "", | |
}; | |
firebase.initializeApp(config); | |
// Use mobx observable | |
const state = observable({ | |
messages: undefined | |
}); | |
// Get ref to messages and watch for changes | |
const ref = firebase.database().ref('messages'); | |
ref.on('value', snap => { | |
state.messages = snap.val(); | |
}); | |
// To remove | |
const remove = (k) => ref.child(k).set(null); | |
// Display all messages | |
autorun(() => { | |
if (!state.messages) return "Loading..."; | |
return <div>{ | |
_.map(state.messages, | |
(m, k) => | |
<div onClick={() => remove(k)}>{m}</div>) | |
}</div>; | |
}); | |
// Set up controls to add new messages | |
let input; | |
const addMessage = () => { | |
ref.push(input.value); | |
input.value = ""; | |
}; | |
<input style={{ fontSize: 30 }} ref={r => input = r}/>; | |
<button onClick={addMessage}>Add</button> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment