how to update profile modal data in react.js

41 Views Asked by At

I'm creating a social media app where i want to display the current user profile info, the data response is being send correctly as in my browser network tabs it says 204 response, but i find it hard how to update data upon editing profile info, when i try to write something in the firstname and lastnam input field it displays no error and when i write something in my worksAt field it displays props error: cannot destructure property, as undefined

here is my InfoCard.jsx compoenent

import React, { useEffect, useState } from "react";
import "./InfoCard.css";
import ProfileModal from "../profileModal/ProfileModal";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "react-router-dom";
import * as UserApi from "../../api/UserRequest.js";
import { logOut } from "../../actions/AuthAction.js";
//import ProfileModal from "../profileModal/ProfileModal";

const InfoCard = () => {
  const dispatch = useDispatch();
  const params = useParams();
  const profileUserId = params.id;
  const [profileUser, setProfileUser] = useState({});
  const { user } = useSelector((state) => state.AuthReducer.authData); // getting it from authReducer file
   

  
  useEffect(() => {
    console.log(user);
    const fetchProfileUser = async () => {
      try {
        if (profileUserId === user._id) {
          setProfileUser(user);
       
        } else {
          const profileUser = await UserApi.getUser(profileUserId);
          setProfileUser(profileUser);
         
        }
      } catch (error) {
        console.error("Error fetching profile user:", error);
      }
    };
    fetchProfileUser();
    console.log(profileUser)
  }, [user, profileUserId]);

  const handleLogout = () => {
    dispatch(logOut());
    console.log("User logged out");
  };
  console.log("InfoCard render - profileUser:", profileUser);


  return (
    <div className="InfoCard">
      <div className="infoHead">
        <h4>Your Info</h4>
        {user._id === profileUserId && (
          <div>
            <ProfileModal profileUser = {user} /> // here is the modal 
          </div>
        )}
      </div>
      <div className="info">
        <span>
          <b>Status </b>
        </span>

        <span>{profileUser.relationship}</span>
      </div>
      <div className="info">
        <span>
          <b>Lives in </b>
        </span>
        <span>{profileUser.livesin}</span>
      </div>
      <div className="info">
        <span>
          <b>Works at </b>
        </span>
        <span>{profileUser.worksAt}</span>
      </div>
      <button className="button logout-button" onClick={handleLogout}>
        Logout
      </button>
    </div>
  );
};


export default InfoCard;

so in here were destructuring user from auth reducer and assigning it to profileUser and usign the profileUser as a prop passed to profileModal.jsx

// profile modal.jsx
in this compoenent im passing profileUser as a parameter and then assigning it to other state and then assiging the other to formData state,

import React from "react";
import Button from "react-bootstrap/Button";
import Modal from "react-bootstrap/Modal";
import { useState } from "react";
import { UilPen } from "@iconscout/react-unicons";
import Form from "react-bootstrap/Form";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "react-router-dom";
import { UploadImage } from "../../actions/UploadAction";
import { UpdateUser } from "../../actions/UserAction";

function ProfileModal({ profileUser }) {
  const [show, setShow] = useState(false);
  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);
  const params = useParams()
  const dispatch = useDispatch()
  const {password, ...other} = profileUser;
  const [formData, setFormData] = useState(other)
  const [profileImage, setProfileImage]  = useState(null)
  const [coverImage, setCoverImage] = useState(null)
  const { user } = useSelector((state) => state.AuthReducer.authData);

  const handleChange = (e) => {
    setFormData({...formData, [e.target.name]: e.target.value})
  }

const onImageChange = (e) => {
  if (e.target.files && e.target.files[0]) {
    let img = e.target.files[0];
    e.target.name === "profileImage"
    ? setProfileImage(img)
    : setCoverImage(img)
  }
}

const handleSubmit = (e) => {
  e.preventDefault()
  let userData = formData 
  if (profileImage) {
    const data = new FormData();
    const fileName = Date.now() + profileImage.name;
    data.append("name", fileName);
    data.append("file", profileImage);
    userData.profilePicture = fileName;
    try {
      dispatch(UploadImage(data));
    } catch (err) {
      console.log(err);
    }
  }

  if(coverImage) {
    const data = new FormData()
    const fileName = Date.now() + profileImage.name
    data.append("name", fileName)
    data.append("file", profileImage)
    userData.profileImage = fileName
    try {
      dispatch(UploadImage(data))
    } catch (err) {
      console.log(err);
    }
  }

  dispatch(UpdateUser(params.id, userData))
  alert("Successfully updated")
}

  return (
    <>
      <UilPen
        width="2rem"
        height="1.2rem"
        variant="primary"
        onClick={handleShow}
      />
      <Modal
        dialogClassName="modal-dialog modal-xl modal"
        size="xxl"
        aria-labelledby="contained-modal-title-vcenter "
        centered
        show={show}
        onHide={handleClose}
      >
        <Modal.Header closeButton>
          <Modal.Title>Your Info</Modal.Title>
        </Modal.Header>
        <Modal.Body
          style={{ maxHeight: "70vh", overflowY: "auto" }}
          className="modal-body"
        >
          <Form>
            <Form.Group className="mb-3" controlId="exampleForm.ControlInput1">
              <Form.Label>First Name</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your first name"
                className="border-0 bg-input p-3"
                name="firstname"
                onChange={handleChange}
                value={formData.firstName}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput2">
              <Form.Label>Last Name</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your last name"
                className="border-0 bg-input p-3"
                name="lastname"
                onChange={handleChange}
                value={formData.lastName}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput3">
              <Form.Label>Works at</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your workplace"
                className="border-0 bg-input p-3"
                name="worksAt"
                onChange={handleChange}
                value={formData.worksAt}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput4">
              <Form.Label>Lives In</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your location"
                className="border-0 bg-input p-3"
                name="livesin"
                onChange={(e) => handleChange(e)}
                value={formData.livesin}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput5">
              <Form.Label>Country</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your country"
                className="border-0 bg-input p-3"
                name="country"
                onChange={handleChange}
                value={formData.country}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput6">
              <Form.Label>Relationship Status</Form.Label>
              <Form.Control
                type="text"
                placeholder="Enter your relationship status"
                className="border-0 bg-input p-3"
                name="relationship"
                onChange={handleChange}
                value={formData.relationship}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group
              className="mb-3"
              controlId="exampleForm.ControlTextarea1"
            >
              <Form.Label>About</Form.Label>
              <Form.Control
                className="border-0 bg-input p-3"
                as="textarea"
                placeholder="Tell us about yourself"
                rows={3}
                name="about"
                onChange={handleChange}
                value={formData.about}
                style={{
                  backgroundColor: "var(--inputColor)",
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput7">
              <Form.Label>Profile Image</Form.Label>
              <Form.Control
                type="file"
                name="profileImage"
                onChange={onImageChange}
                style={{
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>

            <Form.Group className="mb-3" controlId="exampleForm.ControlInput8">
              <Form.Label>Cover Image</Form.Label>
              <Form.Control
                type="file"
                name="coverImage"
                onChange={onImageChange}
                style={{
                  outline: "none",
                  boxShadow: "none",
                  padding: "10px 15px", // Adjust the padding as needed
                }}
              />
            </Form.Group>
          </Form>
        </Modal.Body>

        <Modal.Footer>
          <button className="button info-btn " onClick={(e) => handleSubmit(e)}>Update</button>
        </Modal.Footer>
      </Modal>
    </>
  );
}


export default ProfileModal;

here in profile modal it gives error when i write something in worksAt field that profileUser is undefined cannot be destructured

0

There are 0 best solutions below