sei-ec-remote / team-project-issues

0 stars 0 forks source link

Propblem in getting user as a prop in Update #143

Closed RitaHC closed 1 year ago

RitaHC commented 1 year ago

Describe the bug A clear and concise description of what the bug is.

I'm unable ti import user and its propertied as a prop on the update page. It shows props are null

What is the problem you are trying to solve?

Trying to use the user as a prop to auto fill the form

Expected behavior A clear and concise description of what you expected to happen.

when props are console logged, the user appears

What is the actual behavior? A clear and concise description of what actually happened.

Props = null

Post any code you think might be relevant (one fenced block per file) BACKEND CALL

router.get('/update/:userId', requireToken, (req,res)=> {
    const userId = req.params.userId
    User.findById(userId)
        .then(errors.handle404)
        .then(user=> {
            console.log(user)
            res.json({user:user})
        })
})

router.patch('/update/:userId', requireToken, (req, res, next) => {
    // using userId to avoid using it directly in find to avoid '_.id' issues
    const userId = req.params.userId
    // const userId = req.user.id
    console.log(` ========= This is USERID =========`, userId)

    User.findByIdAndUpdate(userId, { $set: req.body.credentials }, { new: true })
      .then((updatedUser) => {
        if (!updatedUser) {
          throw new Error(`User with id ${userId} not found`)
        }

        console.log(`========= UPDATED USER =======`, updatedUser);
        res.json({ message: 'User updated successfully', user: updatedUser })
      })
      .catch((err) => {
        console.error(err)
        res.status(500).json({ message: err.message })
      })
  })

FRONTEND

// APP.JS
<Route
    path='/update/:userId'
    element={<Update user={user} />}
/>

//  API CALL

export const updateProfile = (user, updatedUser) => {
    console.log(`---updatedProfile API --- userId`,updatedUser.id)
    return axios({
      url: `${apiUrl}/update/${updatedUser.id}`, // Include userId in the URL
      method: 'PATCH',
      headers: {
        Authorization: `Token token=${user.token}`,
      },
      data: { credentials: updatedUser } // Use the correct key for the updated user object
    })
  }

  // Update User Component

  import { useState } from "react";
import LoadingScreen from "../shared/LoadingScreen";
// import { Link } from "react-router-dom";
import { userProfile, signUp } from "../../api/auth";
import messages from '../shared/AutoDismissAlert/messages'
import { Navigate, useNavigate } from "react-router-dom";

const Update = props => {

    const { user } = props

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [passwordConfirmation, setPasswordConfirmation] = useState('');
    const [name, setName] = useState('');
    const [profilePicture, setProfilePicture] = useState('');
    const [coverPicture, setCoverPicture] = useState('');
    const [description, setDescription] = useState('');
    const [active, setActive] = useState(false);

    const navigate = useNavigate();
    console.log(`UPDATE PAGE PROPS`, props)

    const onUpdate = (event) => {
        event.preventDefault();

        const { msgAlert, user, setUser } = props;

        const updatedUser = {
          ...user,
          name,
          profilePicture,
          coverPicture,
          description
        };
        console.log(`Updated User`, updatedUser)

        signUp(updatedUser)
        .then((res) => setUser(res.data.user))
        .then(() => {
            msgAlert({
            heading: 'Update Success',
            message: messages.updateSuccess,
            variant: 'success'
            });
        })
        .catch((error) => {
            setName(user.name);
            setProfilePicture(user.profilePicture);
            setCoverPicture(user.coverPicture);
            setDescription(user.description);
            msgAlert({
            heading: `Update Failed with error: ${error.message}`,
            message: messages.updateFailure,
            variant: 'danger'
            });
        });
    }

    return(
        <>
            UPDATE USER ID
        </>
    )

}

export default Update

What is your best guess as to the source of the problem?

props not getting transfereed, though on the screen the url is corrctely visible and we are at the correct page

What things have you already tried to solve the problem?

Self, Online, Team work all. Stuck since yesterday

Additional context Add any other context about the problem here.

Screenshot 2023-02-16 at 9 46 26 AM Screenshot 2023-02-16 at 9 46 50 AM

Paste a link to your repository here FrontEnd https://github.com/RitaHC/Social-Media-Clone-Front-End/tree/userF

asands94 commented 1 year ago

Do a console.log for user and not props since it looks like you destructured it. Also it looks like you are destructuring props twice here.

RitaHC commented 1 year ago

1) Corrected and destructured just once 2) console logged the user

CODE

    const { msgAlert, user, setUser } = props;

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [passwordConfirmation, setPasswordConfirmation] = useState('');
    const [name, setName] = useState('');
    const [profilePicture, setProfilePicture] = useState('');
    const [coverPicture, setCoverPicture] = useState('');
    const [description, setDescription] = useState('');
    const [active, setActive] = useState(false);

    const navigate = useNavigate();
    console.log(`UPDATE PAGE user`, user)

STILL SAME - NULL

Screenshot 2023-02-16 at 10 05 56 AM
asands94 commented 1 year ago

Make sure you are passing in user into your update component. Where is user coming from?

RitaHC commented 1 year ago

It is coming from ShowProfile

import React from 'react'
// Import API Call
import { userProfile } from '../../api/auth'
import { useState, useEffect } from 'react'
import { Card, Container, Button } from "react-bootstrap"
import LoadingScreen from '../shared/LoadingScreen'

import ListGroup from 'react-bootstrap/ListGroup'
import Update from './Update'

const ShowProfile = (props) => {
    // Define user

    const { user } = props
    console.log(`---------- USER PROP ---------`,props)
    // // console.log(`User Name`, user.name)
    if(!user){
        return <p> <LoadingScreen /> </p>
    }

    return (
    <div>
    <Card>
        User Profile
        {user._id}
        <Card.Img id='imagecover' variant="top" src={user.coverPicture} />

    <Card style={{ width: '18rem' }}>
      <Card.Img variant="top" src={user.profilePicture} />
      <Card.Body>
        <Card.Title>{user.name}</Card.Title>
        <Card.Text>
          {user.description}
        </Card.Text>
      </Card.Body>
      <ListGroup className="list-group-flush">
        <ListGroup.Item>Location: {user.city}</ListGroup.Item>
        <ListGroup.Item>Dapibus ac facilisis in</ListGroup.Item>
        <ListGroup.Item>Vestibulum at eros</ListGroup.Item>
      </ListGroup>
      <Card.Body>
      <Card.Link href={`/update/${user._id}`}><Button>Update Details</Button></Card.Link>
        <Card.Link href="#">Another Link</Card.Link>
      </Card.Body>

      <Update user={user}/>

    </Card>
    </Card>

    </div>
  )
}
asands94 commented 1 year ago

Do you get the user information showing on this page?

RitaHC commented 1 year ago

Yes, getting it there

RitaHC commented 1 year ago

I tried removing it from the Show page and passed it in the app.js as a prop

But it not working. Could we get on a quick call to check that, I'm sure you'll get it in a sec

RitaHC commented 1 year ago

Issue Resolved:

THANK YOUUUUUUU ASHLEYYYYYYYY

Below is the corrected code

Bootstrap issue

<Link to={`/update/${user._id}`}>Update Details</Link> <br />