React Native Project with NodeJS and MongoDB- Part 1

React Native
expo init RNnodeMongo
SignUp.js
App.js
SignUp.js
import { StyleSheet, Text, View, TextInput, TouchableOpacity, Image } from 'react-native'
import React, { useState } from 'react'
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";

const SignIn = () => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleSubmit = async () => {
if (name === '' || email === '' || password === '') {
alert("All fields are required");
return;
}
await axios.post("http://localhost:8001/api/signin", { name, email, password });
alert("Sign In Successful");
};
return (
<KeyboardAwareScrollView contentCotainerStyle={styles.container}>
<View style={{ marginVertical: 100 }}>
<View style={styles.imageContainer}>
<Image source={require("../assets/logo.png")} style={styles.imageStyles} />
</View>
<Text style={styles.signupText}>Sign In</Text>
<View style={{ marginHorizontal: 24 }}>
<Text style={{ fontSize: 16, color: '#8e93a1' }}>EMAIL</Text>
<TextInput style={styles.signupInput} value={email} onChangeText={text => setEmail(text)} autoCompleteType="email" keyboardType="email-address" />
</View>
<View style={{ marginHorizontal: 24 }}>
<Text style={{ fontSize: 16, color: '#8e93a1' }}>PASSWORD</Text>
<TextInput style={styles.signupInput} value={password} onChangeText={text => setPassword(text)} secureTextEntry={true} autoComplteType="password" />
</View>
<TouchableOpacity onPress={handleSubmit} style={styles.buttonStyle}>
<Text style={styles.buttonText}>Submit</Text>
</TouchableOpacity>
<Text style={{ fontSize: 12, textAlign: 'center' }}>Not yet registered? Sign Up</Text>
<Text style={{ fontSize: 12, textAlign: 'center', marginTop: 10 }}>Forgot Password?</Text>
</View>
</KeyboardAwareScrollView>
)
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center'
},
signupText: {
fontSize: 30,
textAlign: 'center'
},
signupInput: {
borderBottomWidth: 0.5,
height: 48,
borderBottomColor: "#8e93a1",
marginBottom: 30,
},
buttonStyle: {
backgroundColor: "darkmagenta",
height: 50,
marginBottom: 20,
justifyContent: "center",
marginHorizontal: 15,
borderRadius: 15,
},
buttonText: {
fontSize: 20,
textAlign: 'center',
color: '#fff',
textTransform: 'uppercase',
fontWeight: 'bold'
},
imageContainer: { justifyContent: "center", alignItems: "center" },
imageStyles: { width: 100, height: 100, marginVertical: 20 }
})

export default SignIn
npm install @react-navigation/native
expo install react-native-screens react-native-safe-area-context
npm install @react-navigation/native-stack
App.js
SignIn.js
SignUp.js
npm i express express-jwt jsonwebtoken mongoose morgan nanoid @sendgrid/mail bcrypt cors dotenv esm
index.js
.gitignore
.env
auth.js
import User from "../models/user";import { hashPassword, comparePassword } from "../helpers/auth";import jwt from "jsonwebtoken";import nanoid from "nanoid";// sendgridrequire("dotenv").config();const sgMail = require("@sendgrid/mail");sgMail.setApiKey(process.env.SENDGRID_KEY);export const signup = async (req, res) => {console.log("Signup Hit");try {// validationconst { name, email, password } = req.body;if (!name) {return res.json({error: "Name is required",});}if (!email) {return res.json({error: "Email is required",});}if (!password || password.length < 6) {return res.json({error: "Password is required and should be 6 characters long",});}const exist = await User.findOne({ email });if (exist) {return res.json({error: "Email is taken",});}// hash passwordconst hashedPassword = await hashPassword(password);try {const user = await new User({name,email,password: hashedPassword,}).save();// create signed tokenconst token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, {expiresIn: "7d",});//   console.log(user);const { password, ...rest } = user._doc;return res.json({token,user: rest,});} catch (err) {console.log(err);}} catch (err) {console.log(err);}};export const signin = async (req, res) => {// console.log(req.body);try {const { email, password } = req.body;// check if our db has user with that emailconst user = await User.findOne({ email });if (!user) {return res.json({error: "No user found",});}// check passwordconst match = await comparePassword(password, user.password);if (!match) {return res.json({error: "Wrong password",});}// create signed tokenconst token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, {expiresIn: "7d",});user.password = undefined;user.secret = undefined;res.json({token,user,});} catch (err) {console.log(err);return res.status(400).send("Error. Try again.");}};export const forgotPassword = async (req, res) => {const { email } = req.body;// find user by emailconst user = await User.findOne({ email });console.log("USER ===> ", user);if (!user) {return res.json({ error: "User not found" });}// generate codeconst resetCode = nanoid(5).toUpperCase();// save to dbuser.resetCode = resetCode;user.save();// prepare emailconst emailData = {from: process.env.EMAIL_FROM,to: user.email,subject: "Password reset code",html: "<h1>Your password  reset code is: {resetCode}</h1>"};// send emailtry {const data = await sgMail.send(emailData);console.log(data);res.json({ ok: true });} catch (err) {console.log(err);res.json({ ok: false });}};export const resetPassword = async (req, res) => {try {const { email, password, resetCode } = req.body;// find user based on email and resetCodeconst user = await User.findOne({ email, resetCode });// if user not foundif (!user) {return res.json({ error: "Email or reset code is invalid" });}// if password is shortif (!password || password.length < 6) {return res.json({error: "Password is required and should be 6 characters long",});}// hash passwordconst hashedPassword = await hashPassword(password);user.password = hashedPassword;user.resetCode = "";user.save();return res.json({ ok: true });} catch (err) {console.log(err);}};
auth.js
import mongoose from "mongoose";const { Schema } = mongoose;const userSchema = new Schema({name: {type: String,trim: true,required: true,},email: {type: String,trim: true,required: true,unique: true,},password: {type: String,required: true,min: 6,max: 64,},role: {type: String,default: "Subscriber",},image: {public_id: "",url: "",},resetCode: "",},{ timestamps: true });export default mongoose.model("User", userSchema);
package.json
.env
SignUp.js
SignIn.js
SignIn.js
SignUp.js
SignUp.js
SignIn.js
auth.js
App.js
SignUp.js
SignIn.js
Home.js
App.js

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store