E-commerce project DEMO:
npm run start
Go to localhost:3000
npm i redux-saga
Listening for the actions, Create asynchronous generator functions
// shopSagas
export function* fetchCollectionsAsync() {
yield console.log('........SHOP SAGA........')
try {
const collectionRef = firestore.collection('collections');
const snapshot = yield collectionRef.get();
const collectionsMap = yield call(convertCollectionsSnapshotToMap, snapshot);
yield put(fetchCollectionsSuccess(collectionsMap))
} catch (error) {
yield put(fetchCollectionsFailure(error.message))
}
}
Containers don't render anything, they just pass props down to components
https://firestore.googleapis.com/v1/projects/YOUR_PROJECT_ID/databases/(default)/documents/cities/LA
npm i redux-thunk
Creating fetchCollectionsStartAsync asynchronous action
// shopActions
export const fetchCollectionsStartAsync = () => {
return dispatch => {
const collectionRef = firestore.collection('collections');
dispatch(fetchCollectionsStart())
collectionRef
.get()
.then(
async snapshot => {
const collectionsMap = convertCollectionsSnapshotToMap(snapshot);
dispatch(fetchCollectionsSuccess(collectionsMap))
})
.catch(error => dispatch(fetchCollectionsFailure(error.message)))
}
}
// ShopPage
class ShopPage extends Component {
unsubscribeFromSnapshot = null;
componentDidMount() {
const collectionRef = firestore.collection('collections')
collectionRef.onSnapshot(
async snapshot => convertCollectionsSnapshotToMap(snapshot)
)
}
...
// firebase.utils
export const convertCollectionsSnapshotToMap = collections => {
const transformedCollection = collections.docs.map(doc => {
const {title, items} = doc.data()
return ({
routeName: encodeURI(title.toLowerCase()),
id: doc.id,
title,
items
})
}
)
console.log(transformedCollection)
}
// App.jsx
import {addCollectionAndDocuments, auth, createUserProfileDocument} from "../../firebase/firebase.utils";
import {selectCollectionsForPreview} from "../../redux/shop/shopSelectors";
componentDidMount() {
const {setCurrentUser, collectionsArray} = this.props;
await addCollectionAndDocuments('collections', collectionsArray.map(({title, items}) => ({
title,
items
})))
}
const mapStateToProps = createStructuredSelector({
currentUser: selectCurrentUser,
collectionsArray: selectCollectionsForPreview
})
// src/firebase/firebase.utils.js
export const addCollectionAndDocuments = async (collectionKey, objectsToAdd) => {
const collectionRef = firestore.collection(collectionKey)
const batch = firestore.batch()
objectsToAdd.forEach(obj => {
const newDocRef = collectionRef.doc()
console.log('newDocRef: ', newDocRef)
batch.set(newDocRef, obj)
})
console.log('collectionRef: ', collectionRef)
return await batch.commit()
}
- Go to Dashboard
- Go to API Keys => Publishable key
- Read the docs
- install react-stripe-checkout
npm i react-stripe-checkout
- create separate component
import React from "react";
import StripeCheckout from "react-stripe-checkout";
import imgLogo from '../../images/logo192.png'
export const StripeCheckoutButton = ({price}) => {
const priceForStripe = price * 100;
const publicKey = 'pk_test_o2poQ9xWESfUvuH00ETkLW0Xj';
const onToken = token => {
console.log(token);
alert('Payment Successful')
}
return (
<StripeCheckout
label='Pay Now'
name='React Store'
billingAddress
shippingAddress
image={imgLogo}
description={`Your total is $${price}`}
amount={priceForStripe}
panelLabel='Pay Now'
token={onToken}
stripeKey={publicKey}
/>
)
}
4242424242424242 Visa CVC - Any 3 digits Date - Any future date
5555555555554444 Mastercard CVC - Any 3 digits Date - Any future date
- check logs
yarn add @formcarry/react
npm i @formcarry/react
import { useForm } from '@formcarry/react';
Firebase module
- console
- Firebase => Create Project => Project Overview => Web => R-Store => Register App
- Copy <script> var firebaseConfig = { ... } </script>
- Run
npm i firebase
- Create file
/firebase/firebase.utils.js
- Firebase => Develop => Authentication => Sign-in method => Google => Enable => rename project => Save
- Firebase => Develop => Authentication => Sign-in method => Email & Password => Enable => Save
- Firebase => Develop => Authentication => Sign-in method => Authorized domains => Add domain => Add
- use it on SignIn component:
import {signInWithGoogle} from "../../firebase/firebase.utils";
<CustomButton onClick={signInWithGoogle}>Sign In with Google</CustomButton>
- Firebase => Cloud Firestore => Develop => Database => Create Database => Start in test mode => Enable
- Data => Add Collection => Start a collection => Collection ID: (users) => Next => Document ID (autogenerate) => Field (displayName: Tom) => Save
- TODO: Store Auth user to Cloud Firestore DB
- firebase.utils.js:
import firebase from "firebase/app";
import 'firebase/firestore';
import 'firebase/auth';
const firebaseConfig = {
apiKey: "AIzaSyDFrtyZ1g-BCvZN5t734kjPx3vFNvVoZh8",
authDomain: "r-store-2020.firebaseapp.com",
databaseURL: "https://r-store-2020.firebaseio.com",
projectId: "r-store-2020",
storageBucket: "r-store-2020.appspot.com",
messagingSenderId: "1027074817941",
appId: "1:1027074817941:web:2efe01b00a5abe5d83809c",
measurementId: "G-8HFVZZ2QE6"
};
export const createUserProfileDocument = async (userAuth, additionalData) => {
if (!userAuth) return;
const userRef = firestore.doc(`users/${userAuth.uid}`)
const snapShot = await userRef.get()
console.log(snapShot)
if (!snapShot.exists) {
const {displayName, email} = userAuth;
const createdAt = new Date();
try {
await userRef.set({
displayName,
email,
createdAt,
...additionalData
})
} catch (error) {
console.log('ERROR! (user creating in DB process ...)', error.message)
}
}
return userRef
}
firebase.initializeApp(firebaseConfig);
export const auth = firebase.auth();
export const firestore = firebase.firestore();
const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({prompt: 'select_account'});
export const signInWithGoogle = () => auth.signInWithPopup(provider)
export default firebase;
- App.jsx:
import {auth, createUserProfileDocument} from "../../firebase/firebase.utils";
...
unsubscribeFromAuth = null
componentDidMount() {
this.unsubscribeFromAuth = auth.onAuthStateChanged(async user => {
await createUserProfileDocument(user)
}
);
}
componentWillUnmount() {
this.unsubscribeFromAuth()
}
This project was bootstrapped with Create React App.
In the project directory, you can run:
Runs the app in the development mode.
Open http://localhost:3000 to view it in the browser.
The page will reload if you make edits.
You will also see any lint errors in the console.
Launches the test runner in the interactive watch mode.
See the section about running tests for more information.
Builds the app for production to the build
folder.
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.
Your app is ready to be deployed!
See the section about deployment for more information.
Note: this is a one-way operation. Once you eject
, you can’t go back!
If you aren’t satisfied with the build tool and configuration choices, you can eject
at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject
will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use eject
. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
You can learn more in the Create React App documentation.
To learn React, check out the React documentation.
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify