I found a great tutorial on using React with Firebase for a very simple use of just storing a text field's data in a database, but I'm stumped on how to convert it to using Hooks. There aren't many tutorials I could find out there on using Hooks + Firebase, so I'd appreciate any help!
import React, {useState} from 'react'
import fire from './fire'
import './App.css'
const App = () => {
let [messageList, setMessageList] = useState([])
const handleSubmit = (e) => {
e.preventDefault()
}
return(
<section>
<form onSubmit={handleSubmit}>
<input type="text"></input>
<button>Test</button>
</form>
<span>Messages: {messageList}</span>
</section>
)
}
class ThisWorksButNotWithHooks extends React.Component {
constructor(props) {
super(props);
this.state = { messages: [] }; // <- set up react state
}
componentWillMount(){
/* Create reference to messages in Firebase Database */
let messagesRef = fire.database().ref('messages').orderByKey().limitToLast(100);
messagesRef.on('child_added', snapshot => {
/* Update React state when message is added at Firebase Database */
let message = { text: snapshot.val(), id: snapshot.key };
this.setState({ messages: [message].concat(this.state.messages) });
})
}
addMessage(e){
e.preventDefault(); // <- prevent form submit from reloading the page
/* Send the message to Firebase */
fire.database().ref('messages').push( this.inputEl.value );
this.inputEl.value = ''; // <- clear the input
}
render() {
return (
<form onSubmit={this.addMessage.bind(this)}>
<input type="text" ref={ el => this.inputEl = el }/>
<input type="submit"/>
<ul>
{ /* Render the list of messages */
this.state.messages.map( message => <li key={message.id}>{message.text}</li> )
}
</ul>
</form>
);
}
}
export default App;
I know it's communicating with Firebase properly because ThisWorksButNotWithHooks works, thanks to https://www.codementor.io/yurio/all-you-need-is-react-firebase-4v7g9p4kf . I learn best by seeing a barebones simple example and working up from there by trial and error, so if I knew how to do this with Hooks I could work up to more complex usage.
Thank you!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…