Home > OS >  Why array post data pushed in wrong user?
Why array post data pushed in wrong user?

Time:12-11

I'm trying to solve this problem entire day.. I'm creating 'likes' system, but one part of my code not working correctly. What I'm trying to do is when user is logged he can see displayed user on main page. He can like or dislike him.

For example: Bob pressed like button on John profile, so Bob should get John (as an object) in his liked array. By the way all data are pushing to MongoDB. But the problem is that when Bob press like button, John has been pushed to John liked array, not in Bob. Next step when Bob already liked him, next user displayed for example Garry, so if he liked Garry too, so Garry is pushed to John liked array. Not in Bob or Garry. I've never had any problem like this.. I'll add my code below.

I hope anyone could help me with that.. Thank you!

back-end ( mainController ) :

updateLikes: async (req, res) => {
        const { secret } = req.params
        const likesObj = req.body
        const updateUser = await UserSchema.findOneAndUpdate(secret, { $push: { likes: likesObj } }, { returnDocument: 'after' })
        console.log(secret)
        await updateUser.save()
        return res.send({ error: false, message: 'Likes updated!', data: null })
    },
    updateLiked: async (req, res) => {
        const { secret } = req.params
        const likedObj = req.body
        const updateLiked = await UserSchema.findOneAndUpdate(secret, { $push: { liked: likedObj } }, { returnDocument: 'after' })
        console.log(secret)
        await updateLiked.save()
        return res.send({ error: false, message: 'Liked updated!', data: null })
    },

There's where I'm using post:

import React, { useState, useEffect } from 'react';
import { Link, useParams, useNavigate } from 'react-router-dom';
import Toolbar from '../components/Toolbar';
import { get, post } from '../helper/helper';

export default function TestPage() {

    const [current, setCurrent] = useState()
    const [index, setIndex] = useState(0);
    const [allUsers, getAllUsers] = useState([])
    const localSecret = window.localStorage.getItem('secret')
    const nav = useNavigate()
    const { user } = useParams()

    useEffect(() => {
        async function currentUser() {
            const resp = await get(`user/${localSecret}`)
            setCurrent(resp.data)
        }
        currentUser()
    }, [])

    useEffect(() => {
        async function fetchUsers() {
            const resp = await get('api')
            resp.filter(user => user.secret !== localSecret)
            getAllUsers(resp)
        }
        fetchUsers()
    }, [])

    const currentUser = allUsers[index];

    // Other user likes array
    async function postLikes() {
        await post(current, `likes/${user}`)
        console.log('current.data likes', current)
        console.log('user likes', user)
        console.log('likes post req', await post(current, `likes/${user}`))
    }
// Current user liked array
    async function postLiked() {
        await post(currentUser, `liked/${localSecret}`)
        console.log('currentUser liked', currentUser)
        console.log('localSecret', localSecret)
        console.log('post liked', await post(currentUser, `liked/${localSecret}`))
    }

    async function postDislike() {
        await post(currentUser, `dislike/${localSecret}`)
    }


    return (
        <div className='home__page'>
            <Toolbar />
            <div className="home__users">
                <div className='single__user'>
                    <img src={currentUser && currentUser.image[0]} alt="" />
                    <h3>{currentUser && `${currentUser.firstName} ${currentUser.lastName}`}</h3>
                    <h4>{currentUser && currentUser.gender}</h4>
                    <button onClick={() => { setIndex(index   1); postDislike(); nav(`/${currentUser.secret}`) }}>Dislike</button>
                    <button onClick={() => { setIndex(index   1); postLiked(); postLikes(); nav(`/${currentUser.secret}`) }}>Like</button>
                </div>
            </div>
            <footer className='footer'>
                <p>All rights reserved by Cartoon Match organization. To read more about our policy <Link to='/policy'>click here</Link>. </p>
            </footer>
        </div>
    )
}

CodePudding user response:

Think about improving the name of your variables. current, currentUser, and user are hard to tell apart. Could you explain to me what the difference between those 3 variables are? Maybe that way we could help you better.

CodePudding user response:

The problem was, that I was using in mainController:

const updateUser = await UserSchema.findOneAndUpdate( secret , { $push: { likes: likesObj } }, { returnDocument: 'after' })

So I just added in findOneAndUpdate curly bracket on secret like this {secret} and this is where my whole problem was..

  • Related