Create a gist now

Instantly share code, notes, and snippets.

How to create a React.js ticketing system using Redux-Form and a MongoDB
//server/controllers/_ticket-control.js
'use strict';
const Tickets = require('../models/tickets');
//===================
// Create Tickets Route
//===================
exports.createTicket = function(req, res, next) {
const name = req.body.name;
const email = req.body.email;
const message = req.body.message;
if (!name) {
return res.status(422).send({ error: 'You must enter a name!'});
}
if (!email) {
return res.status(422).send({ error: 'You must enter your email!'});
}
if (!message) {
return res.status(422).send({ error: 'You must enter a detailed description of what you need!'});
}
let ticket = new Tickets({
name: name,
email: email,
status: "Open",
message: message
});
ticket.save(function(err, user) {
if(err) {return next(err);}
res.status(201).json({ message: "Thanks! Your request was submitted successfuly!" });
next();
})
}
//client/actions/index.js
//import
import axios from 'axios';
import { SUBMIT_TICKET, ERROR_RESPONSE } from './types';
// server route
const API_URL = 'http://localhost:3000/api';
export function errorHandler(error) {
return {
type: ERROR_RESPONSE,
payload: error
};
}
//================================
// TICKET ACTIONS
//================================
export function submitTicket({name, email, message}) {
return function(dispatch) {
axios.post(`${API_URL}/tickets/create-new-ticket`, {name, email, message}
)
.then(response => {
dispatch({
type: SUBMIT_TICKET,
payload: response.data
});
})
.catch(response => dispatch(errorHandler(response.data.error)))
}
}
//server router.js
//import dependencies
const express = require('express'),
// import controllers
const _ticketController = require('./controllers/_ticket-control');
module.exports = function(app) {
const ticketRoutes = express.Router();
//==================
// TICKET ROUTES
//==================
apiRoutes.use('/tickets', ticketRoutes);
ticketRoutes.post('/create-new-ticket', requireAuth, _ticketController.createTicket);
app.use('/api', apiRoutes);
}
//server/index.js
// Importing Node modules and initializing Express
const express = require('express'),
app = express(),
router = require('./router'),
cors = require('cors'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
config = require('./config/main');
//always use environment variables to store this information
//and call it in a seperate file.
const databse = 'mongodb://username:password@location.mlab.com:port/database'
// Database Setup
mongoose.connect(config.database);
// Import routes to be served
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
router(app);
// Start the server
app.listen(config.port);
console.log('Your server is running on port ' + config.port + '.');
//client/components/ticket_form.js
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import * as actions from '../../actions';
const form = reduxForm({
form: 'tickets'
});
const renderField = field => (
<div>
<div className="input_container">
<input className="form-control" {...field.input}/>
</div>
{field.touched && field.error && <div className="error">{field.error}</div>}
</div>
);
const renderTextArea = field => (
<div>
<div className="input_container">
<textarea {...field.input}/>
</div>
{field.touched && field.error && <div className="error">{field.error}</div>}
</div>
);
class TicketForm extends Component {
handleFormSubmit(formProps) {
this.props.submitTicket(formProps);
this.props.initialize('');
}
render() {
const { handleSubmit } = this.props;
return (
<div>
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<label>Name:</label>
<Field name="name" type="text" component={renderField}/>
<label>Email:</label>
<Field name="email" type="email" component={renderField}/>
<label>Tell us in detail about the problem:</label>
<Field name="message" type="text" component={renderTextArea}/>
<button action="submit" className="button">Save changes</button>
</form>
</div>
)
}
}
function mapStateToProps(state) {
return {
formValues: state.form
};
}
export default connect(mapStateToProps, actions)(form(TicketForm));
//server/models/tickets.js
// Importing packages that are required for this
// schema
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
//================================
// Ticketing Schema
//================================
const TicketSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
status: {
type: String,
required: true
},
message: {
type: String,
required: true
}
}, {
timestamps: true
});
module.exports = mongoose.model('Tickets', TicketSchema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment