[bug]: save right value to favs db

This commit is contained in:
Ruidy Nemausat 2020-04-28 11:20:44 +02:00
parent e664753691
commit 7fd605fd5d
6 changed files with 45 additions and 28 deletions

View file

@ -50,7 +50,7 @@ Free meal planner for cooks short on ideas! (like me …)
- Unknown - Unknown
- Vietnamese - Vietnamese
- Cocktail selection - Cocktail selection
- Create a profile and save your favourite meals - Create a profile and save your favourite meals
- Notation system: know what are the most loved meals - Notation system: know what are the most loved meals
- Share recipe with your friends and family - Share recipe with your friends and family
- Suggestions based on what your personal taste - Suggestions based on what your personal taste
@ -79,6 +79,7 @@ The application is hosted on [Render](https://render.com/) at the following addr
- [TheMealDb](https://www.themealdb.com/api.php) - An open, crowd-sourced database of Recipes from around the world - [TheMealDb](https://www.themealdb.com/api.php) - An open, crowd-sourced database of Recipes from around the world
<!-- - and [TheCocktailDb](https://www.thecocktaildb.com/api.php) --> <!-- - and [TheCocktailDb](https://www.thecocktaildb.com/api.php) -->
- [Auth0](https://auth0.com/) - Rapidly integrate authentication and authorization - [Auth0](https://auth0.com/) - Rapidly integrate authentication and authorization
- [Firebase](https://firebase.google.com/) - Firebase helps mobile and web app teams succeed
- [Render](https://render.com/) - The Easiest Cloud For All Your Apps and Websites - [Render](https://render.com/) - The Easiest Cloud For All Your Apps and Websites
<!-- - Analytics : Google Analytics & Mixpanel --> <!-- - Analytics : Google Analytics & Mixpanel -->

View file

@ -9,7 +9,7 @@ export const MealPresentation = ({ meal }) => {
mealCategory, mealCategory,
mealArea, mealArea,
isFav, isFav,
setIsFav, handleFavChange,
} = meal; } = meal;
return ( return (
@ -48,10 +48,7 @@ export const MealPresentation = ({ meal }) => {
{" "} {" "}
<i <i
className="material-icons tiny" className="material-icons tiny"
onClick={(e) => { onClick={handleFavChange}
e.preventDefault();
setIsFav(!isFav);
}}
> >
{isFav ? "favorite" : "favorite_border"} {isFav ? "favorite" : "favorite_border"}
</i> </i>

View file

@ -1,18 +1,14 @@
import React from "react"; import React from "react";
import { Switch, Route, Redirect } from "react-router-dom"; import { Switch, Route, Redirect } from "react-router-dom";
import { SearchController } from "../controllers/SearchController"; import { SearchController } from "../controllers/SearchController";
import { HomeController } from "../controllers/HomeController"; import { HomeController } from "../controllers/HomeController";
import { MealController } from "../controllers/MealController"; import { MealController } from "../controllers/MealController";
import { CategoryController } from "../controllers/CategoryController"; import { CategoryController } from "../controllers/CategoryController";
import { CategoryListController } from "../controllers/CategoryListController"; import { CategoryListController } from "../controllers/CategoryListController";
import { ProfileController } from "../controllers/ProfileController"; import { ProfileController } from "../controllers/ProfileController";
import { ContactPage } from "../pages/Contact"; import { ContactPage } from "../pages/Contact";
import { NotFoundPage } from "../pages/NotFoundPage"; import { NotFoundPage } from "../pages/NotFoundPage";
import { PrivateRoute } from "../components/PrivateRoute"; import { PrivateRoute } from "../components/PrivateRoute";
import TestPage from "../pages/TestPage";
const MainRouter = ({ const MainRouter = ({
buttonUrl, buttonUrl,

View file

@ -27,14 +27,24 @@ export const MealController = ({ meal, getMeal, getRandomMeal }) => {
strInstructions, strInstructions,
} = mealItem; } = mealItem;
const [isFav, setIsFav] = useState(false); const [isFav, setIsFav] = useState();
/**
* Updates fav status in db
*/
const handleFavChange = (e) => {
e.preventDefault();
setIsFav(!isFav);
// Send !isFav because state is not yet updated
fb.addToFavs(user.email, idMeal, strMeal, strMealThumb, !isFav);
};
useEffect(() => { useEffect(() => {
// Not update fav status of the placeholder recipe. TODO: it's ugly... // Not update fav status of the placeholder recipe. TODO: it's ugly...
if (idMeal !== "52837" && isAuthenticated) { if (idMeal !== "52837" && isAuthenticated) {
fb.addToFavs(user.email, idMeal, strMeal, strMealThumb, isFav); fb.isFav(user.email, idMeal).then((res) => setIsFav(res));
} }
}, [user, idMeal, strMeal, strMealThumb, isFav, fb, isAuthenticated]); }, [user.email, fb, idMeal, isAuthenticated]);
const item = { const item = {
mealName: strMeal, mealName: strMeal,
@ -42,15 +52,15 @@ export const MealController = ({ meal, getMeal, getRandomMeal }) => {
videoAddress: strYoutube, videoAddress: strYoutube,
mealCategory: strCategory, mealCategory: strCategory,
mealArea: strArea, mealArea: strArea,
isFav: isFav, isFav,
setIsFav: setIsFav, handleFavChange,
}; };
let ingredientList = []; let ingredientList = [];
var i; var i;
for (i = 1; i <= 20; i++) { for (i = 1; i <= 20; i++) {
var strIng = `strIngredient${i}`; let strIng = `strIngredient${i}`;
var strMes = `strMeasure${i}`; let strMes = `strMeasure${i}`;
if (mealItem[strIng] !== "" && mealItem[strIng] !== null) { if (mealItem[strIng] !== "" && mealItem[strIng] !== null) {
ingredientList.push([mealItem[strIng], mealItem[strMes]]); ingredientList.push([mealItem[strIng], mealItem[strMes]]);
} }

View file

@ -16,7 +16,7 @@ export const ProfilePage = ({ user, data }) => {
<div className="row"> <div className="row">
<b>Email: </b> <b>Email: </b>
{user.email} {user.email}
<br /> <h3>Favourites meals</h3>
<ul>{data && data.map((d, i) => <CardEntry key={i} item={d} />)}</ul> <ul>{data && data.map((d, i) => <CardEntry key={i} item={d} />)}</ul>
</div> </div>
</div> </div>

View file

@ -1,16 +1,15 @@
import app from "firebase/app"; import app from "firebase/app";
import "firebase/firestore"; import "firebase/firestore";
import config from "./config.json";
const CONFIG = { const CONFIG = {
apiKey: config.apiKey, apiKey: process.env.API_KEY,
authDomain: config.authDomain, authDomain: process.env.AUTH_DOMAIN,
databaseURL: config.databaseURL, databaseURL: process.env.DB_URL,
projectId: config.projectId, projectId: process.env.PROJECT_ID,
storageBucket: config.storageBucket, storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: config.messagingSenderId, messagingSenderId: process.env.MSG_SENDER_ID,
appId: config.appId, appId: process.env.APP_ID,
measurementId: config.measurementId, measurementId: process.env.MEASUREMENT_ID,
}; };
const FAVS = "favs"; const FAVS = "favs";
@ -48,6 +47,7 @@ export default class Firebase {
const query = await this.collection const query = await this.collection
.doc(email) .doc(email)
.collection(FAVS) .collection(FAVS)
.where("isFav", "==", true)
// .orderBy("timestamp", "desc") // .orderBy("timestamp", "desc")
.limit(10) .limit(10)
.get(); .get();
@ -57,6 +57,19 @@ export default class Firebase {
return favs; return favs;
}; };
isFav = async (email, idMeal) => {
const query = await this.collection
.doc(email)
.collection(FAVS)
.doc(idMeal)
.get();
const obj = query.data();
return obj && !!obj.isFav;
// .where("isFav", "==", true);
// return !!query;
};
/** /**
* Create or update favourite status for an authenticated user. * Create or update favourite status for an authenticated user.
*/ */
@ -73,7 +86,7 @@ export default class Firebase {
isFav, isFav,
// timestamp: app.FieldValue.serverTimestamp(), // timestamp: app.FieldValue.serverTimestamp(),
}) })
// .then(() => console.log("Fav object created.")) // .then(() => console.log("Fav object created.", isFav))
.catch((err) => console.error("Error adding favs to database", err)); .catch((err) => console.error("Error adding favs to database", err));
}; };
} }