Jeg gætter på, at du skal bruge databasen på serveren, så du skal muligvis bruge en API for at sende dataene, da databasen ikke er på klienten. Jeg bruger Superagent for at sende dataene og Mongoose at oprette et skema og en mongo-database.
messageModel.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// create a schema
const messageSchema = new Schema({
// You may need to add other fields like owner
addedOn: String,
message: String,
});
const Message = mongoose.model('Message', messageSchema);
module.exports = Message;
server.js
import Message from './models/messageModel';
mongoose.connect('mongodb://user:[email protected]:port/database');
app.post('/api/messages', (req, res) => {
const doc = new Message({ message: req.body.message })
doc.save();
});
client.js
import React, { Component } from 'react';
import request from 'superagent';
class componentName extends Component {
constructor(props) {
super(props);
this.state = {
message: '',
};
this.handleMessageInput = this.handleMessageInput.bind(this);
}
handleMessageInput(e) {
this.setState({ message: e.target.value });
}
handleSubmitMessage() {
console.log('starting to submit profile');
if (this.state.isFormFilledProfile) {
console.log('Profile Form appears filled');
const data = {
message: this.state.message,
};
request
.post('/api/messages')
.send(data)
.set('Accept', 'application/json')
.end((err, res) => {
if (err || !res.ok) {
console.log('Oh no! err');
} else {
console.log('Success');
}
});
}
}
render() {
return (
<div>
<div>
<form onSubmit={this.handleSubmitMessage}>
<input
onChange={this.handleMessageInput}
value={this.state.message}
/>
<button type='Submit' value='Submit'>Submit</button>
</form>
</div>
</div>
);
}
}
export default componentName;
Du skal muligvis også gennemgå react forms guiden her. Alt det bedste!!!