'why does my result always return as false

I'm using mern to set up a social media of sorts. I'm trying to do if a post is favourited then it should be true if not false. However the result for favourited is always false regardless of if the post is in the users likes in the DB.

If the post has been favourited the button is meant to be set to show the word removed, that way the user knows they've favourited it. If its not favourited(false) it should show add. However, if the user favourites a post and likes it then refreshes the page instead of showing remove it shows add and if the user adds it again it then adds the same movie to the DB.

favourite routes

const express =  require('express');
const router = express.Router();
const { authJwt } = require("../middlewares");
const Favourite = require("../models/favourite.model");

    router.use(function(req, res, next) {
      res.header(
        "Access-Control-Allow-Headers",
        "x-access-token, Origin, Content-Type, Accept"
      );
      next();
});


router.post("/favouriteNumber", [authJwt.verifyToken], (req, res) => {
    Favourite.find({"movieId": req.body.movieId})
        .exec((err, favourite) => {
            if(err) return res.status(400).send(err)
            res.status(200).json({success: true, favouriteNumber: favourite.length})
        })
})

router.post("/favourited", [authJwt.verifyToken], (req, res) => {
    Favourite.find({"movieId": req.body.movieId, "userFrom": req.body.userFrom})
        .exec((err, favourite) => {
            if(err) return res.status(400).send(err) 

            let result = false;
            if(favourite.length !== 0) {
                result = true
            }

            res.status(200).json({success: true, favourited: result});


        })
})

router.post("/addToFavourite", [authJwt.verifyToken], (req, res) => {
    
    const favourite = new Favourite(req.body)

    favourite.save((err, doc) => {
        if(err) return res.json({success: false, err})
        return res.status(200).json({success: true, doc})
    })
})

router.post("/removeFavorite", [authJwt.verifyToken], (req, res) => {
    
    Favourite.findOneAndDelete({movieId: req.body.movieId, userFrom: req.body.userFrom})
        .exec((err, doc) => {
            if(err) return res.json({success: false, err})
            return res.status(200).json({success: true, doc})
        })
})

router.post("/getFavourites", [authJwt.verifyToken], (req, res) => {
    Favourite.find({ userFrom: req.body.data }) 
    .populate('userFrom')
    .exec((err, films) => {
        if(err) return res.status(400).send(err)
        res.status(200).json({success: true, films})
    })
    
    
})
module.exports = router;

favourite component

import Axios from 'axios';
import React, { useEffect, useState } from 'react'
import styled from "styled-components";
import authService from '../../services/auth.service';
import authHeader from '../../services/auth-header';

const FavouriteButton = styled.button`
  height: 30px;
  width: 40px;
`;

function FavouriteComp(props) {

    const currentUser = authService.getCurrentUser();

    const [favourited, setFavourited] =  useState(false);

    const variable = {
        userFrom: currentUser.id,
        movieId: props.movieInfo?.id,
        movieTitle: props.movieInfo?.title,
        movieImg: props.movieInfo?.poster_path
    }

    const onClickFavourite = () => {
        //if user already likes the film - remove it
        if(favourited) {
            Axios.post('http://localhost:8080/api/favourite/removeFavorite', variable, { headers: authHeader() })
                .then(response =>{
                    if(response.data.success){
                        setFavourited(!favourited)
                        console.log("Removed from favourites")
                    }else {
                        alert('Failed to remove');
                    }
                })

                //if not -  add to favourites
        }else {
            Axios.post('http://localhost:8080/api/favourite/addToFavourite', variable, { headers: authHeader() })
                .then(response =>{
                    if(response.data.success){
                        setFavourited(!favourited)
                        console.log("Added to favourites")
                    }else {
                        alert('Failed to add');
                    }
                })
        }
    }

    useEffect(() => {
        Axios.post('http://localhost:8080/api/favourite/favourited', variable, { headers: authHeader() }) 
            .then(response =>{
                if(response.data.success){
                    // setFavourited(response.data.favourited)
                    // console.log(response.data)
                }else {
                    alert('Failed to get info');
                }
            })

    }, [])


    return (
        <div>
            <FavouriteButton onClick={onClickFavourite}>{!favourited ? "add" : "remove"}</FavouriteButton>
        </div>
    )
}

export default FavouriteComp


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source