Whatever is the application you are building, the data is in the heart of it. In this post I will go through building a simple but functional form with Formik and storing the data to Firebase database. I will use React functional component for this example so you can follow along or use it with your React project.
Prerequisites
- First you will need to create a Project at Firebase (or use an existing one).
- You need to create a database within the Firebase project you want to use (or use an existing one) and set up the write rule to
true
. - React application (using Create React App or other)
- Following packages (you can also use
npm i
instead ofyarn add
):
$ yarn add firebase formik
Configure Firebase
When you arrive to your Firebase dashboard you will enter your project and grab a configuration object by pressing the code icon </>
Then you will get something similar to this:
firebaseConfig.js
var firebaseConfig = {
apiKey: "xxxxxxxx",
authDomain: "firebaseformikproject-xxxxx.firebaseapp.com",
projectId: "firebaseformikproject-xxxxx",
storageBucket: "firebaseformikproject-xxxxx.appspot.com",
messagingSenderId: "xxxxxxxxxxxxx",
appId: "x:xxxxxxxxxxx:web:xxxxxxxxxxxxxxxxxx"
};
We will use this object to configure Firebase in our React app.
Create a new file in your project directory/src named firebaseConfig.js
and paste the object.
Next replace var
with let
and add export default firebaseConfig
outside of the object
Go to the index.js
or entry point of your application and add following line above of ReactDOM.render()
:
index.js
...
import { firebase } from '@firebase/app';
import firebaseConfig from './firebaseConfig';
firebase.initializeApp(firebaseConfig);
ReactDOM.render(
...
Note: If your firebaseConfig.js
file is not in the same directory as your index.js
then you have to adjust the route in the import statement.
Now the Firebase initializes on your application start.
Add Formik form
We will now create a simple form with Formik. Create a new file named RegisterForm.js
and place it into current directory.
We will use React, Firebase for updating the database and Formik hook for handling the form so we need to import them:
RegisterForm.js
import React from 'react'
import Firebase from 'firebase'
import { useFormik } from 'formik'
Next we will pass initial values and the onSubmit method to our functional component. We will ask our users to write their first name, username, and email. We will then save that data in the Firebase database when the user clicks submit:
RegisterForm.js
...
const RegisterForm = () => {
const formik = useFormik({
initialValues: {
firstName: '',
username: '',
email: '',
},
onSubmit: values => {
let ref1 = Firebase.database().ref().child('users').push()
ref1.set(values)
},
});
return (
<form onSubmit={formik.handleSubmit}>
<label htmlFor="firstName">First Name</label>
<input
id="firstName"
name="firstName"
type="text"
onChange={formik.handleChange}
value={formik.values.firstName}
/>
<label htmlFor="username">Username</label>
<input
id="username"
name="username"
type="text"
onChange={formik.handleChange}
value={formik.values.username}
/>
<label htmlFor="email">Email Address</label>
<input
id="email"
name="email"
type="email"
onChange={formik.handleChange}
value={formik.values.email}
/>
<button type="submit">Submit</button>
</form>
);
};
export default RegisterForm
And voila! Our registration form is ready and working. We used Formik helper functions handleChange
and handleSubmit
so it kept our code quite clean.
If you want to test it, open App.js and import RegisterForm.js
and use it as a component.
App.js
import RegisterForm from "./RegisterForm";
export default function App() {
return (
<div className="App">
<RegisterForm />
</div>
);
}
Firebase and unique ID
If you worked with relational databases you are familiar with the id for each entry that is usually a primary key i.e. it is unique and can be referred only to one entry.
In Firebase each entry gets a unique key so one our example entries looks like this:
users
|_ -MEIwCAwrPBePyp4mVv1
|_ firstName: "John"
|_ username: "johnwayne"
|_ email: "john.w@mail.com"
Each new entry gets this unique key, but what if you want to catch it and store it along with all the data for one user? It is simple, we will just edit our onSubmit method:
RegisterForm.js
...
onSubmit: values => {
let ref1 = Firebase.database().ref().child('users').push()
let key = ref1.key
values.id = key
ref1.set(values)
},
...
We first grab a key from our ref1
and then we put that value to the values object. We will then have this in the database:
users
|_ -MEIwCAwrPBePyp4mVv1
|_ firstName: "John"
|_ username: "johnwayne"
|_ email: "john.w@mail.com"
|_ id: "-MEIwCAwrPBePyp4mVv1"
We can use this key to find and target the particular user with specific child.
Formik is a great tool for creating efficient forms while firebase offers quick setup and authentication options, deployment is also easy to setup through github actions.
Thank you for reading!
Top comments (0)