Skip to content

Instantly share code, notes, and snippets.

@oampo
Created April 19, 2018 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oampo/e8337298f8dfa6518871f79d966b531e to your computer and use it in GitHub Desktop.
Save oampo/e8337298f8dfa6518871f79d966b531e to your computer and use it in GitHub Desktop.
import React from 'react';
import {reduxForm, Field, SubmissionError} from 'redux-form';
import Input from './input';
import {required, nonEmpty, exactLength, onlyNumbers} from './validators';
const exactLength5 = exactLength(5);
const API_BASE_URL =
process.env.REACT_APP_API_BASE_URL || 'http://localhost:8080/api';
export class DeliveryForm extends React.Component {
onSubmit(values) {
return fetch(`${API_BASE_URL}/report`, {
method: 'POST',
body: JSON.stringify(values),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
if (!res.ok) {
if (
res.headers.has('content-type') &&
res.headers
.get('content-type')
.startsWith('application/json')
) {
// It's a nice JSON error returned by us, so decode it
return res.json().then(err => Promise.reject(err));
}
// It's a less informative error returned by express
return Promise.reject({
code: res.status,
message: res.statusText
});
}
return;
})
.then(() => console.log('Submitted with values', values))
.catch(err => {
const {reason, message, location} = err;
if (reason === 'ValidationError') {
// Convert ValidationErrors into SubmissionErrors for Redux Form
return Promise.reject(
new SubmissionError({
[location]: message
})
);
}
return Promise.reject(
new SubmissionError({
_error: message
})
);
});
}
render() {
let successMessage;
if (this.props.submitSucceeded) {
successMessage = (
<div className="message message-success">
Report submitted successfully
</div>
);
}
let errorMessage;
if (this.props.error) {
errorMessage = (
<div className="message message-error">{this.props.error}</div>
);
}
return (
<div className="delivery-form">
<h2>Report a problem with your delivery</h2>
<form
onSubmit={this.props.handleSubmit(values =>
this.onSubmit(values)
)}>
{successMessage}
{errorMessage}
<Field
name="trackingNumber"
id="trackingNumber"
label="Tracking number"
component={Input}
validate={[
required,
nonEmpty,
exactLength5,
onlyNumbers
]}
/>
<Field
name="issue"
id="issue"
label="What is your issue?"
component={Input}
element="select">
<option value="not-delivered">
My delivery hasn't arrived
</option>
<option value="wrong-item">
The wrong item was delivered
</option>
<option value="missing-part">
Part of my order was missing
</option>
<option value="damaged">
Some of my order arrived damaged
</option>
<option value="other">
Other (give details below)
</option>
</Field>
<Field
name="details"
id="details"
label="Give more details (optional)"
component={Input}
element="textarea"
/>
<button type="submit">Submit</button>
</form>
</div>
);
}
}
export default reduxForm({
form: 'delivery',
initialValues: {
issue: 'not-delivered'
}
})(DeliveryForm);
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import './index.css';
import store from './store';
import DeliveryForm from './delivery-form';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<Provider store={store}>
<DeliveryForm />
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
import React from 'react';
export default class Input extends React.Component {
componentDidUpdate(prevProps) {
if (!prevProps.meta.active && this.props.meta.active) {
this.input.focus();
}
}
render() {
const Element = this.props.element || 'input';
let error;
if (this.props.meta.touched && this.props.meta.error) {
error = <div className="form-error">{this.props.meta.error}</div>;
}
let warning;
if (this.props.meta.touched && this.props.meta.warning) {
warning = (
<div className="form-warning">{this.props.meta.warning}</div>
);
}
return (
<div className="form-input">
<label htmlFor={this.props.input.name}>
{this.props.label}
{error}
{warning}
</label>
<Element
{...this.props.input}
id={this.props.input.name}
type={this.props.type}
ref={input => (this.input = input)}>
{this.props.children}
</Element>
</div>
);
}
}
// In production, we register a service worker to serve assets from local cache.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://goo.gl/SC7cgQ'
);
});
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
import {createStore, combineReducers} from 'redux';
import {reducer as formReducer} from 'redux-form';
export default createStore(
combineReducers({
form: formReducer
})
);
export const required = value => (value ? undefined : 'Required');
export const nonEmpty = value =>
value.trim() !== '' ? undefined : 'Cannot be empty';
export const exactLength = length => value =>
value.length === length
? undefined
: `Must contain exactly ${length} characters`;
export const onlyNumbers = value =>
/^\d+$/.test(value) ? undefined : 'Must only contain numbers';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment