Last active
June 26, 2019 14:57
-
-
Save brookslybrand/a118411f3847e75e45bbb6dc558d0e86 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 React, { useEffect, useState } from 'react' | |
| import { Offline, Online } from 'react-detect-offline' | |
| // some inline styling so everything isn't squished | |
| const formStyle = { padding: '2rem 0rem' } | |
| const inputStyle = { margin: '1rem 0rem' } | |
| // a simple form with a first name, last name, and submit button | |
| const Form = ({ db }) => { | |
| // store form values in a state hook | |
| const [names, setNames] = useState({ firstname: '', lastname: '' }) | |
| useEffect( | |
| () => { | |
| // create the store | |
| db.version(1).stores({ formData: 'id,value' }) | |
| }, | |
| // run effect whenever the database connection changes | |
| [db] | |
| ) | |
| // sets the name in the store and in the state hook | |
| const setName = id => value => { | |
| console.log(db) | |
| // update the store | |
| db.formData.put({ id, value }) | |
| // update the state hook | |
| setNames(prevNames => ({ ...prevNames, [id]: value })) | |
| } | |
| // partial application to make on change handler easier to deal with | |
| const handleSetName = id => e => setName(id)(e.target.value) | |
| // when the form is submitted, prevent the default action | |
| // which reloads the page and reset the first and last name | |
| // in both the store and in the state hook | |
| const handleSubmit = e => { | |
| e.preventDefault() | |
| setName('firstname')('') | |
| setName('lastname')('') | |
| } | |
| return ( | |
| <form style={formStyle} onSubmit={handleSubmit}> | |
| <span>First name:</span> | |
| <br /> | |
| <input | |
| style={inputStyle} | |
| type="text" | |
| name="firstname" | |
| value={names.firstname} | |
| onChange={handleSetName('firstname')} | |
| /> | |
| <br /> | |
| <span>Last name:</span> | |
| <br /> | |
| <input | |
| style={inputStyle} | |
| type="text" | |
| name="lastname" | |
| value={names.lastname} | |
| onChange={handleSetName('lastname')} | |
| /> | |
| <br /> | |
| {/* Handle whether or not the user is offline */} | |
| <Online> | |
| <input type="submit" value="Submit" /> | |
| </Online> | |
| <Offline>You are currently offline!</Offline> | |
| </form> | |
| ) | |
| } | |
| export default Form |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment