Facebook Pixel

Netflix Clone với ReactJS, Styled Components và Firebase (Firestore & Auth) - Phần 5

04 Dec, 2021

Trong phần 5 này, chúng ta sẽ hoàn thiện Guest Home Page và config để connect với firebase, chuẩn bị cho các phần tiếp theo nhé 😉.

Netflix Clone với ReactJS, Styled Components và Firebase (Firestore & Auth) - Phần 5

Mục Lục

Trong phần 5 này, chúng ta sẽ hoàn thiện Guest Home Page và config để connect với firebase, chuẩn bị cho các phần tiếp theo nhé 😉.

I. Create Header component.

Trong folder components ta tạo thêm component header như sau:

Header component folder

Trong file header.jsx ta code như sau:

JavaScript
import styled from "styled-components/macro";
import { Link } from "react-router-dom";

export const Container = styled.div`
	transition: background-color 0.5s;
	position: relative;
	max-width: 1920px;
	margin: 0 auto;
	padding-top: 20px;
	width: 100%;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 10;
	height: 4rem;
`;

export const Background = styled.div`
	display: flex;
	flex-direction: column;
	border-bottom: 8px solid #222;
	width: 100%;
	object-fit: cover;
	background: linear-gradient(
			to top,
			rgba(0, 0, 0, 0.8) 0,
			rgba(0, 0, 0, 0) 60%,
			rgba(0, 0, 0, 0.8) 100%
		),
		url(${({ src }) =>
				src
					? `../images/misc/${src}.jpg`
					: "../images/misc/home-bg.jpg"})
			top left / cover no-repeat;
`;

export const Wrapper = styled.div`
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	height: auto;
	padding-top: 0.5rem;
	position: relative;
	margin: 0 3.5rem;
`;

export const Logo = styled.img`
	width: auto;
	height: 1.5rem;
	padding-top: 0;
	@media only screen and (min-width: 950px) and (max-width: 1449px) {
		width: 8.375rem;
		height: 2.25rem;
	}
	@media only screen and (min-width: 1450px) {
		width: 10.4375rem;
		height: 2.8125rem;
	}
`;

export const ButtonLink = styled(Link)`
	display: block;
	background-color: #e50914;
	color: #fff;
	border: 0;
	border-radius: 3px;
	padding: 8px 17px;
	cursor: pointer;
	text-decoration: none;
	font-size: 1rem;
	font-weight: 400;
	white-space: nowrap;

	&:hover {
		background-color: #f40612;
	}
`;
export const WrapBlock = styled.div`
	display: flex;
`;

export const WrapSelect = styled.div`
	position: relative;
	display: inline-block;
	width: 100%;
	margin: 0 0.75rem;
	&::before {
		content: "\f0ac";
		font-family: "Font Awesome 5 Free";
		font-weight: 900;
		position: absolute;
		transform: translateY(-50%);
		top: 50%;
		left: 0.5rem;
		color: #fff;
		font-size: 0.75rem;
		pointer-events: none;
	}
`;

export const Select = styled.select`
	padding: 0.5rem 1.375rem;
	background-color: rgba(0, 0, 0, 0.4);
	border: 1px solid #aaa;
	color: #fff;
	font-size: 0.875rem;
	border-radius: 2px;
	width: 80%;

	@media only screen and (min-width: 550px) and (max-width: 949px),
		only screen and (min-width: 950px) and (max-width: 1449px),
		only screen and (min-width: 1450px) {
		padding: 0.5rem 1.375rem;
	}
`;
export const Option = styled.option``;
header.jsx

Trong /header/index.jsx ta thêm code như sau:

JavaScript
import React from "react";
import { Link } from "react-router-dom";
import {
	Background,
	Container,
	Logo,
	ButtonLink,
	Wrapper,
	Select,
	Option,
	WrapSelect,
	WrapBlock
} from "./styles/header";

export default function Header({ bg = true, children, ...restProps }) {
	return bg ? <Background {...restProps}>{children}</Background> : children;
}

Header.Frame = function HeaderFrame({ children, ...restProps }) {
	return <Container {...restProps}>{children}</Container>;
};

Header.Wrapper = function HeaderWrapper({ children, ...restProps }) {
	return <Wrapper {...restProps}>{children}</Wrapper>;
};

Header.ButtonLink = function HeaderButtonLink({ children, ...restProps }) {
	return <ButtonLink {...restProps}>{children}</ButtonLink>;
};

Header.Logo = function HeaderLogo({ to, ...restProps }) {
	return (
		<Link to={to}>
			<Logo {...restProps} />
		</Link>
	);
};

Header.WrapBlock = function HeaderWrapBlock({ children, ...restProps }) {
	return <WrapBlock {...restProps}>{children}</WrapBlock>;
};

Header.WrapSelect = function HeaderWrapSelect({ children, ...restProps }) {
	return <WrapSelect {...restProps}>{children}</WrapSelect>;
};

Header.Select = function HeaderSelect({ children, ...restProps }) {
	return <Select {...restProps}>{children}</Select>;
};

Header.Option = function HeaderOption({ children, ...restProps }) {
	return <Option {...restProps}>{children}</Option>;
};
index.jsx

File ảnh backgroundlogo, các bạn có thể tải tại đây.

Tiếp tục, tạo thêm file headerContainer.jsx trong folder containers và thêm đoạn code như sau:

JavaScript
import React from "react";
import { Header } from "../components/index";
import * as ROUTES from "../constants/routes";

export default function HeaderContainer({ children }) {
	return (
		<Header>
			<Header.Frame>
				<Header.Wrapper>
					<Header.Logo
						to={ROUTES.HOME}
						alt="Netflix-clone"
						src="/images/logo.svg"
					/>
					<Header.WrapBlock>
						<Header.WrapSelect>
							<Header.Select>
								<Header.Option value="/vn-en/">
									English
								</Header.Option>
								<Header.Option value="/vn/">
									Vietnamese
								</Header.Option>
							</Header.Select>
						</Header.WrapSelect>
						<Header.ButtonLink to={ROUTES.SIGN_IN}>
							Sign In
						</Header.ButtonLink>
					</Header.WrapBlock>
				</Header.Wrapper>
			</Header.Frame>
			{children}
		</Header>
	);
}
headerContainer.jsx

Trong /pages/home.jsx ta thêm phần header vừa rồi như bên dưới:

JavaScript
import React from "react";
import {
	StoryContainer,
	FAQsContainer,
	FooterContainer,
	HeaderContainer
} from "../containers/index";
import { OptionForm } from "../components/index";

export default function Home() {
	return (
		<>
			{/* Header */}
			<HeaderContainer>
				<OptionForm>
					<OptionForm.WrapContent>
						<OptionForm.Title>
							Unlimited movies, TV shows, and more.
						</OptionForm.Title>
						<OptionForm.SubTitle>
							Watch anywhere. Cancel anytime.
						</OptionForm.SubTitle>
						<OptionForm.Break />
						<OptionForm.Text>
							Ready to watch? Enter your email to create or
							restart your membership.
						</OptionForm.Text>
						<OptionForm.WrapForm>
							<OptionForm.Input placeholder="Email address" />
							<OptionForm.Button>Get Started</OptionForm.Button>
						</OptionForm.WrapForm>
					</OptionForm.WrapContent>
				</OptionForm>
			</HeaderContainer>
			<StoryContainer />
			<FAQsContainer />
			<FooterContainer />
		</>
	);
}
home.jsx

Okie! run thử xem chạy có ổn không nhé, nếu được như hình dưới thì đã okie rồi.

Header UI

II. Connect with firebase.

Để có thể connect vơi firebase, đầu tiên ta cần tạo một firebase project trước đã 😁, nếu bạn chưa từng sử dụng firebase trước đây thì trước tiên bạn cần đăng ký một account với firebase nhé, sau đó làm theo hướng dẫn như bên dưới.

  • Step 1: Sau khi vào được trang chủ của firebase bằng account của mình, click vào Go to console như hình.
Step 1
  • Step 2: Sau khi thực hiện xong step 1, ta sẽ thấy UI phần Your Firebase projects của các bạn (Ở đây của mình có 2 cái project cá nhân nên nó sẽ như hình), các bạn click vào Add project để tiến hành tạo project của mình.
Step 2
  • Step 3: Sau khi thực hiện step 2, firebase sẽ cho chúng ta 2 step nhỏ hơn:

   - Step 3.1: Phần này là đặt tên, bạn có thể đặt tên tùy ý hoặc cũng có thể đặt tên như hình dưới.

Step 3.1

   - Step 3.2: Ở bước này chúng ta không cần sử dụng Google Analytics nên tắt nó đi thôi.

Step 3.2
  • Step 4: Sau khi xong hết step 3, chúng ta sẽ được như hình, chọn phần Firestore Database để tiến hành tạo một Cloud database, lưu trữ những data cần thiết.
Step 4
  • Step 5: Click vào button Create database.
Step 5
  • Step 6: Chọn Start in test mode, bất kỳ ai cũng truy cập và thao tác được với database của chúng ta (chọn mode này để có thể sử dụng được lâu hơn 😁) → click Next để sang step tiếp theo.
Step 6
  • Step 7: Chọn server lưu trữ data của chúng ta, ở đây mình để default là được → click button Enable.
Step 7

Okie! Vậy là đã setup xong phần firebase project của chúng ta, để project của chúng ta connect được với firebase ta phải config nó như sau:

  • Trong folder src tạo folder và file như sau: /src/lib/firebase.prod.js và thêm đoạn code như sau:
JavaScript
import Firebase from "firebase/compat/app";
import "firebase/compat/firestore";
import "firebase/compat/auth";

const config = {};

const firebase = Firebase.initializeApp(config);

export { firebase };
firebase.prod.js

Config tạm thời như vậy trước, giờ ta quay lại với firebase, chúng ta tiến hành thêm firebase vào web app của chúng ta, các bạn làm như sau:

  • Step 1: Click vào icon web này.
Step 1
  • Step 2: Nhập tên firebase project của bạn đã tạo trước đó vào và nhấn vào button Register app như hình.
Step 2
  • Step 3: Sau khi xong step 2, firebase sẽ cung cấp cho chúng ta đoạn script để config với project của chúng ta như hình, copy đoạn script như hình nhé.
Step 3
  • Step 4: Paste đoạn script vào file /lib/firebase.prod.js như bên dưới.
JavaScript
import Firebase from "firebase/compat/app";
import "firebase/compat/firestore";
import "firebase/compat/auth";

const config = {			
	apiKey: "***************************************",				
	authDomain: "***********************************",
	projectId: "*******************",				   
	storageBucket: "*******************************",
	messagingSenderId: "************",
	appId: "****************************************"
};

const firebase = Firebase.initializeApp(config);

export { firebase };
Step 4 - firebase.prod.js

Như vậy, chúng ta đã config và connect với firebase xong, tiếp theo chúng ta sẽ add data lên Cloud Firestore của firebase. Chúng ta có thể add trực tiếp bằng tay ở phần Cloud Firestore của firebase như hình bên dưới.

Cloud Firestore

Tuy nhiên chúng ta sẽ không add thủ công như vậy, làm vậy sẽ rất là lâu, do đó các bạn làm như sau:

  • Trong folder src tạo thêm file /src/seedData.js và thêm đoạn code như sau:
JavaScript
export function seedData(firebase) {
	function getUUID() {
		return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
			const pieceID = (Math.random() * 16) | 0;
			const UUID = c === "x" ? pieceID : (pieceID & 0x3) | 0x8;
			return UUID.toString(16);
		});
	}

	/* Series
============================================ */
	// Documentaries
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Tiger King",
		description:
			"An exploration of big cat breeding and its bizarre underworld, populated by eccentric characters.",
		genre: "documentaries",
		maturity: "18",
		slug: "tiger-king"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Amanda Knox",
		description:
			"Amanda Marie Knox is an American woman who spent almost four years in an Italian prison.",
		genre: "documentaries",
		maturity: "12",
		slug: "amanda-knox"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Citizenfour",
		description:
			"Citizenfour is a 2014 documentary film directed by Laura Poitras, concerning Edward Snowden and the NSA spying scandal.",
		genre: "documentaries",
		maturity: "12",
		slug: "citizenfour"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Super Size Me",
		description:
			"Director Morgan Spurlock's social experiment in fast-food gastronomy sees him attempting to subsist uniquely on food from the McDonalds",
		genre: "documentaries",
		maturity: "12",
		slug: "super-size-me"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Man on Wire",
		description:
			"Filmmaker James Marsh masterfully recreates high-wire daredevil Philippe Petit's 1974 stunt walking on a wire across the Twin Towers.",
		genre: "documentaries",
		maturity: "12",
		slug: "man-on-wire"
	});

	// Comedies
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "The Office",
		description:
			"A motley group of office workers go through hilarious misadventures at the Scranton, Pennsylvania, branch of the Dunder Mifflin Paper Company.",
		genre: "comedies",
		maturity: "15",
		slug: "the-office"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Arrested Development",
		description:
			"The Bluth family, once a prominent name in the business, loses everything after the head patriarch gets convicted for fraud.",
		genre: "comedies",
		maturity: "15",
		slug: "arrested-development"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Curb Your Enthusiasm",
		description:
			"Larry David, a famous television writer and producer, gets into various misadventures with his friends and celebrity colleagues in Los Angeles.",
		genre: "comedies",
		maturity: "15",
		slug: "curb-your-enthusiasm"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Family Guy",
		description:
			"Peter Griffin and his family of two teenagers, a smart dog, a devilish baby and his wife find themselves in some of the most hilarious scenarios.",
		genre: "comedies",
		maturity: "15",
		slug: "family-guy"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "South Park",
		description:
			"Four young, schoolgoing boys, Stan Marsh, Kyle Broflovski, Eric Cartman and Kenny McCormick, who live in South Park set out on various adventures.",
		genre: "comedies",
		maturity: "15",
		slug: "south-park"
	});

	// Children
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Peppa Pig",
		description:
			"Peppa, an outgoing preschool pig, participates in many energetic activities. She learns something new every day and has a lot of fun with her family and friends.",
		genre: "children",
		maturity: "0",
		slug: "peppa-pig"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Dora The Explorer",
		description:
			"Dora, a seven-year-old girl of Latin American descent, embarks upon numerous adventures in the wilderness with her friend Boots, a monkey, and a variety of fun and useful tools.",
		genre: "children",
		maturity: "0",
		slug: "dora-the-explorer"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "PAW Patrol",
		description:
			"Six brave puppies, captained by a tech-savvy ten-year-old boy, Ryder, work together to accomplish high-stakes rescue missions to safeguard the residents of the Adventure Bay community.",
		genre: "children",
		maturity: "0",
		slug: "paw-patrol"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Arthur",
		description:
			"Bespectacled aardvark Arthur Read demonstrates to kids how to deal with such childhood traumas and challenges as homework, teachers and bullies.",
		genre: "children",
		maturity: "0",
		slug: "arthur"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "SpongeBob",
		description:
			"A yellow sea sponge named SpongeBob SquarePants lives in the city of Bikini Bottom deep in the Pacific Ocean. ",
		genre: "children",
		maturity: "0",
		slug: "spongebob"
	});

	// Crime
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Making a Murderer",
		description:
			"Exonerated after spending nearly two decades in prison for a crime he did not commit, Steven Avery filed suit against Manitowoc County, Wis., and several individuals involved with his arrest.",
		genre: "crime",
		maturity: "18",
		slug: "making-a-murderer"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Long Shot",
		description:
			"An innocent man is accused of murder, leading his attorney on a wild chase to confirm his alibi using raw footage from a television show.",
		genre: "crime",
		maturity: "18",
		slug: "long-shot"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "The Confession Killer",
		description:
			"Henry Lee Lucas was an American convicted serial killer whose crimes spanned from 1960 to 1983. He was convicted of murdering eleven people and condemned to death for the murder of Debra Jackson, although his sentence would be commuted to life in prison in 1998.",
		genre: "crime",
		maturity: "18",
		slug: "the-confession-killer"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "The Innocent Man",
		description:
			"Henry Lee Lucas was an American convicted serial killer whose crimes spanned from 1960 to 1983. He was convicted of murdering eleven people and condemned to death for the murder of Debra Jackson.",
		genre: "crime",
		maturity: "18",
		slug: "the-innocent-man"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "The Staircase",
		description:
			"In 2001 novelist Michael Peterson's wife died, and he claimed she perished after falling down stairs at their home. The medical examiner, however, determined that she had been beaten with a weapon",
		genre: "crime",
		maturity: "18",
		slug: "the-staircase"
	});

	// Feel-good
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Good Will Hunting",
		description:
			"Will Hunting, a genius in mathematics, solves all the difficult mathematical problems. When he faces an emotional crisis, he takes help from psychiatrist Dr Sean Maguireto, who helps him recover.",
		genre: "feel-good",
		maturity: "12",
		slug: "good-will-hunting"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Forrest Gump",
		description:
			"Forrest Gump, a man with a low IQ, joins the army for service where he meets Dan and Bubba. However, he cannot stop thinking about his childhood sweetheart Jenny Curran, whose life is messed up.",
		genre: "feel-good",
		maturity: "12",
		slug: "forrest-gump"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Juno",
		description:
			"Social misfit Juno protects herself with a caustic wit, but her unplanned pregnancy has the teen getting more involved in the lives of her baby's adoptive parents than she expected.",
		genre: "feel-good",
		maturity: "12",
		slug: "juno"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "Midnight In Paris",
		description:
			"Gil arrives with his fiancee and her family in Paris for a vacation, even as he tries to finish his debut novel. He is beguiled by the city, which takes him to a time past, away from his fiancee.",
		genre: "feel-good",
		maturity: "12",
		slug: "midnight-in-paris"
	});
	firebase.firestore().collection("series").add({
		id: getUUID(),
		title: "School of Rock",
		description:
			"Dewey Finn, an amateur rock enthusiast, slyly takes up his friend's substitute teacher's job. Bearing no qualifications for it, he instead starts training the students to form a band.",
		genre: "feel-good",
		maturity: "12",
		slug: "school-of-rock"
	});

	/* Films
    ============================================ */
	// Drama
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "The Prestige",
		description:
			"Two friends and fellow magicians become bitter enemies after a sudden tragedy. As they devote themselves to this rivalry, they make sacrifices that bring them fame but with terrible consequences.",
		genre: "drama",
		maturity: "15",
		slug: "the-prestige"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Fight Club",
		description:
			"Discontented with his capitalistic lifestyle, a white-collared insomniac forms an underground fight club with Tyler, a careless soap salesman. The project soon spirals down into something sinister.",
		genre: "drama",
		maturity: "15",
		slug: "fight-club"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Kings Speech",
		description:
			"King George VI tries to overcome his stammering problem with the help of speech therapist Lionel Logue and makes himself worthy enough to lead his country through World War II.",
		genre: "drama",
		maturity: "15",
		slug: "kings-speech"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "The Revenant",
		description:
			"Hugh Glass, a legendary frontiersman, is severely injured in a bear attack and is abandoned by his hunting crew. He uses his skills to survive and take revenge on his companion, who betrayed him.",
		genre: "drama",
		maturity: "15",
		slug: "the-revenant"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "The Social Network",
		description:
			"Mark Zuckerberg creates a social networking site, Facebook, with the help of his friend Eduardo Saverin. But soon, a string of lies tears their relationship apart even as Facebook connects people.",
		genre: "drama",
		maturity: "12",
		slug: "the-social-network"
	});

	// Suspense
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Shutter Island",
		description:
			"Teddy Daniels and Chuck Aule, two US marshals, are sent to an asylum on a remote island in order to investigate the disappearance of a patient, where Teddy uncovers a shocking truth about the place.",
		genre: "suspense",
		maturity: "15",
		slug: "shutter-island"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Gone Girl",
		description:
			"Nick Dunne discovers that the entire media focus has shifted on him when his wife Amy Dunne disappears on the day of their fifth wedding anniversary.",
		genre: "suspense",
		maturity: "15",
		slug: "gone-girl"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Prisoners",
		description:
			"When the police take time to find Keller Dover's daughter and her friend, he decides to go on a search himself. His desperation leads him closer to finding the truth and also jeopardises his own life.",
		genre: "suspense",
		maturity: "15",
		slug: "prisoners"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Seven",
		description:
			"A serial killer begins murdering people according to the seven deadly sins. Two detectives, one new to the city and the other about to retire, are tasked with apprehending the criminal.",
		genre: "suspense",
		maturity: "15",
		slug: "seven"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Zodiac",
		description:
			"Robert Graysmith, a cartoonist by profession, finds himself obsessively thinking about the Zodiac killer. He uses his puzzle-solving abilities to get closer to revealing the identity of the killer.",
		genre: "suspense",
		maturity: "15",
		slug: "zodiac"
	});

	// Children
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Hotel Transylvania",
		description:
			"Dracula, who owns a high-end resort for monsters, attempts to keep his daughter from falling in love with Jonathan, a human.",
		genre: "children",
		maturity: "0",
		slug: "hotel-transylvania"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Despicable Me",
		description:
			"Gru, a criminal mastermind, adopts three orphans as pawns to carry out the biggest heist in history. His life takes an unexpected turn when the little girls see him as their potential father.",
		genre: "children",
		maturity: "0",
		slug: "despicable-me"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Frozen",
		description:
			"Anna sets out on a journey with an iceman, Kristoff, and his reindeer, Sven, in order to find her sister, Elsa, who has the power to convert any object or person into ice.",
		genre: "children",
		maturity: "0",
		slug: "frozen"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Spirited Away",
		description:
			"In this animated feature by noted Japanese director Hayao Miyazaki, 10-year-old Chihiro (Rumi Hiiragi) and her parents (Takashi Naitô, Yasuko Sawaguchi) stumble upon a seemingly abandoned amusement park.",
		genre: "children",
		maturity: "0",
		slug: "spirited-away"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Up",
		description:
			"Carl, an old widower, goes off on an adventure in his flying house in search of Paradise Falls, his wife's dream destination.",
		genre: "children",
		maturity: "0",
		slug: "up"
	});

	// Thriller
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Joker",
		description:
			"Forever alone in a crowd, failed comedian Arthur Fleck seeks connection as he walks the streets of Gotham City.",
		genre: "thriller",
		maturity: "15",
		slug: "joker"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "A Quiet Place",
		description:
			"The Abbott family must now face the terrors of the outside world as they fight for survival in silence. Forced to venture into the unknown, they realize that the creatures that hunt by sound are not the only threats that lurk beyond the sand path.",
		genre: "thriller",
		maturity: "15",
		slug: "a-quiet-place"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Black Swan",
		description:
			"Nina, a ballerina, gets the chance to play the White Swan, Princess Odette. But she finds herself slipping into madness when Thomas, the artistic director, decides that Lily might fit the role better.",
		genre: "thriller",
		maturity: "15",
		slug: "black-swan"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Nightcrawler",
		description:
			"Louis Bloom, a petty thief, realises that he can make money by capturing photographs of criminal activities and starts resorting to extreme tactics to get them.",
		genre: "thriller",
		maturity: "15",
		slug: "nightcrawler"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "The Silence of The Lambs",
		description:
			"Clarice Starling, an FBI agent, seeks help from Hannibal Lecter, a psychopathic serial killer and former psychiatrist, in order to apprehend another serial killer who has been claiming female victims.",
		genre: "thriller",
		maturity: "15",
		slug: "the-silence-of-the-lambs"
	});

	// Romance
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "A Star Is Born",
		description:
			"After falling in love with struggling artist Ally, Jackson, a musician, coaxes her to follow her dreams, while he battles with alcoholism and his personal demons.",
		genre: "romance",
		maturity: "15",
		slug: "a-star-is-born"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Blue Valentine",
		description:
			"Dean and Cynthia are married with a daughter and their marriage is about to fall apart. Both come from dysfunctional families and struggle to make sense of their relationship.",
		genre: "romance",
		maturity: "15",
		slug: "blue-valentine"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "La La Land",
		description:
			"Sebastian (Ryan Gosling) and Mia (Emma Stone) are drawn together by their common desire to do what they love. But as success mounts they are faced with decisions that begin...",
		genre: "romance",
		maturity: "15",
		slug: "la-la-land"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "The Notebook",
		description:
			"Duke reads the story of Allie and Noah, two lovers who were separated by fate, to Ms Hamilton, an old woman who suffers from Alzheimer's, on a daily basis out of his notebook.",
		genre: "romance",
		maturity: "15",
		slug: "the-notebook"
	});
	firebase.firestore().collection("films").add({
		id: getUUID(),
		title: "Titanic",
		description:
			"Seventeen-year-old Rose hails from an aristocratic family and is set to be married. When she boards the Titanic, she meets Jack Dawson, an artist, and falls in love with him.",
		genre: "romance",
		maturity: "15",
		slug: "titanic"
	});
}
seedData.js

Như tên gọi SeedData, nó có một nhiệm vụ duy nhất là add data lên Cloud Firestore cho chúng ta. Giải thích một tý về các đoạn code trên cho các bạn lần đầu làm quen với firebase nhé 😉.

- getUUID(): function giúp chúng ta auto generate ID theo dạng string và id là duy nhất, đây là chỉ là một JS function thông thường thôi. Ex: '0e264c21-96c5-4acd-8be3-b5e41edb04f3'

- firebase.firestore().collection("series").add(): Tham chiếu đến firestore của firebase thực hiện tạo các collectionadd các data vào mỗi collection theo dạng object.

  • Để add các data ta đã chuẩn bị như trên lên Cloud Firestore chúng ta làm như sau:

- Trong file firebase.prod.js ta thêm dòng code như sau:

JavaScript
import { seedData } from "../seedData";

seedData(firebase);
firebase.prod.js

Cloud Firestore ban đầu.

The original Cloud Firestore.

- Tiếp theo, trong file /src/index.js ta edit lại như sau:

JSX
import { firebase } from "./lib/firebase.prod";
index.js

Sau đó chúng ta reload lại trang của Cloud Firestore và được kết quả như hình dưới.

Cloud Firestore after adding data

Tara 😁! À phần seedData là hàng dùng một lần thôi nhé 😁, vì sao lại dùng một lần ? Bởi vì ta đã add thành công data vào Cloud Firestore của firebase rồi nên sẽ không cần nữa, do đó trong file firebase.prod.js, ta bỏ phần seedData đi nhé 😉.

III. Tổng kết.

Bài viết hôm nay đến đây thôi, trong phần này chúng ta đã code xong phần header và cũng hoàn thành luôn phần Guest Home Page, setup và connect với firebase. Đồng thời cũng đã add thành công data lên Cloud Firestore của firebase. Trong phần tiếp theo chúng ta sẽ setup một chút React Context cho firebase và sử dụng Authentication do firebase cung cấp để làm trang Sign In nhé 😉. Cảm ơn các bạn đã đọc, See u again~

Bài viết liên quan

Lập trình backend expressjs

xây dựng hệ thống microservices
  • Kiến trúc Hexagonal và ứng dụngal font-
  • TypeScript: OOP và nguyên lý SOLIDal font-
  • Event-Driven Architecture, Queue & PubSubal font-
  • Basic scalable System Designal font-

Đăng ký nhận thông báo

Đừng bỏ lỡ những bài viết thú vị từ 200Lab