0

I am trying to create a favourite functionality, for now I am trying to get the recipe by it's id and then save the data in const variables and then create a new recipe with the same data and add it to the favourites data collection. It adds a recipe to the favourites page, but it doesn't show the data, it shows only the html model of the recipe. I hope that's clear enough.

 import "./RecipeModel.css";
import { Link, NavLink, useNavigate, useParams } from 'react-router-dom';
import { BrowserRouter,Route,Routes, Switch, Redirect } from 'react-router-dom';
import React, { useLayoutEffect, useState,useEffect, useContext } from 'react';
import * as userService from '../../../services/userService';
import { AuthContext } from "../../../contexts/AuthContext";

const RecipeModel = ({
    recipe
}) => {

    const history = useNavigate();
    const {user} = useContext(AuthContext);
    const {recipeId} = useParams();
    const [recipec,setRecipe] = useState();

    useEffect(() => {
        userService.getOne(recipeId)
        .then(result => {
            setRecipe(result);
        })
            },[recipeId]);
    
    const HandleFavourite = (e) =>  {
        e.preventDefault();

        // const recipesd = async () => {
        //     let reciperes =   await userService.getOne(recipeId);
    
        //     console.log(reciperes);
        //     setRecipe(reciperes);
        //     };
    
        //    useEffect(() => { recipesd(recipec); },[]);

        console.log(`Recipe ${recipec._id}`);
     

        // let recipeData = Object.fromEntries(new FormData(e.currentTarget))

        // userService.addFavourite(recipe._id, recipeData);

        // history('/favourites');

        // const formData = new FormData(e.currentTarget);
    
        const name = recipec.name;
        const time = recipec.time;
        const imageUrl = recipec.imageUrl;
        const ingredients = recipec.ingredients;
        const instructions = recipec.instructions;
    

        userService.addFavourite({
            name,
            time,
            imageUrl,
            ingredients,
            instructions
        },user.accessToken)
         .then(result => {
            console.log(result);
            history('/favourites');
        })
    }
    

    return (
        <article className="articles">
            <img className="img2" src={recipe.imageUrl}/>
            <h1>{recipe.name}</h1>
            <p className="cut-text">{recipe.instructions}</p>
            <div className="btns1">
            <Link  smooth= "true" className="btnd" to={`/recipe-details/recipe-number:${recipe._id}`}>Details</Link>
                <button className="favour" onClick={HandleFavourite} ><i className="fas fa-solid fa-heart-circle-plus"></i></button>
            </div>
        </article>
    );
};

export default RecipeModel;

The method to getOne works fine for the other data collections I fetched.

That's the Favourites component

    import "./Favourites.css";
import { Link, NavLink } from 'react-router-dom';
import { BrowserRouter,Route,Routes, Switch, Redirect } from 'react-router-dom';
import RecipeList  from "../RecipeList/RecipeList";
import CreateRecipe from "../Recipe/CreateRecipe/CreateRecipe";
import React, { useLayoutEffect, useState ,useEffect} from 'react';
import RecipeFavourite from "../Recipe/RecipeFavourite/RecipeFavourite";
import * as recipeService from "../../services/recipeService";
import * as userService from '../../services/userService';

function Favourites() {

    // const [recipes,setRecipes] = useState([]);
     
    // useEffect(() => {
    //     recipeService.getAll()
    //     .then(result => {
    //         setRecipes(result);
    //     })
    // },[]);

    const [favourites,setFavourites] = useState([]);

    useEffect(() => {
        userService.getAllFavourites()
        .then(result => {
            setFavourites(result);
        })
    },[]);

    useLayoutEffect(() => {
        window.scrollTo(0, 0)
    });

    const scrollToTop = () => {
        window.scrollTo(0, 0)
    }

    return (
        <div>
            <h1 className = "h1m">Your Favourite Recipes</h1>
            <section className="secfav">

                
           {favourites.map(x => <RecipeFavourite key ={x._id} recipe={x} />)}
            {/* {recipes.map(x => <RecipeFavourite key ={x._id} recipe={x}/>)} */}
            </section>
        </div>
    );
}

export default Favourites;

Thats's the RecipeFavourite component

    import "./RecipeFavourite.css";
import { Link, NavLink } from 'react-router-dom';
import { BrowserRouter,Route,Routes, Switch, Redirect } from 'react-router-dom';
import React, { useLayoutEffect, useState } from 'react';

const RecipeFavourite = ({recipe,recipes}) => {


    return (
        <article className="articles">
            <img className="img4" src={recipe.imageUrl}/>
            <h1>{recipe.name}</h1>
            <p className="cut-text">{recipe.instructions}</p>
            <div className="btns1">
            <Link  smooth= "true" className="btnd" to={`/recipe-details/recipe-number:${recipe._id}`}>Details</Link>
                <button className="favnon"><i className="fas fa-solid fa-heart-circle-minus"></i></button>
            </div>
        </article>
    );
};

export default RecipeFavourite;

Thats the AuthContext logic

   import { createContext, useContext } from 'react';

export const AuthContext = createContext();

The userService logic

    export const addFavourite = async (recipeData,token) => {
    let response = await fetch(`${baseUrl}/favourites`, {
        method: 'POST',
        headers: {
            'content-type': 'application/json',
            'X-Authorization': token,
        },
        body: JSON.stringify(recipeData)
    });
    
    let  result = await response.json();

    return result;
};

export const getAllFavourites = async () => {
    let response = await fetch(`${baseUrl}/favourites`)

    let recipes = await response.json();

    let result = Object.values(recipes);

    return result;
}
DimitriTfb
  • 49
  • 9
  • Can you also please show us what the userContext file looks like? This looks as though it should work correctly, but I think that might help – Brett East Jul 29 '22 at 12:33
  • Sorry, I meant the userService logic, the file that is fetching and storing the recipes and favourites – Brett East Jul 29 '22 at 12:37
  • I added it, I don't think the problem is there, it's very simple logic inside it, the data i use requires Authentication which i have and edit, create, delete also work fine, and take the data.I added the userService logic, hope it helps – DimitriTfb Jul 29 '22 at 12:39

0 Answers0