Can't update the profile picture using cloudinary - reactjs

I've tried to upload an image in Cloudinary and also want to save it into my database. Uploading an image in Cloudinary works fine but I can't save it into my database. Whenever I tried to do this it's only using the default image I've set in my model. Also likes setPic is working but for a moment and again it's changed to the default image. Please anybody help me figure out this problem.
Please comment if any other details if you need. Please help me.
Here is the Function
const postDetails = (pics) => {
setPicMessage(null);
if (pics?.type === 'image/jpeg' || pics?.type === 'image/png') {
const data = new FormData();
data.append('file', pics);
data.append('upload_preset', 'codeblogger_profile_image');
data.append('cloud_name', 'dhuej17x0');
fetch('https://api.cloudinary.com/v1_1/dhuej17x0/image/upload', {
method: 'post',
body: data,
})
.then((res) => res.json())
.then((data) => {
setPic(data.secure_url.toString());
console.log(pic);
})
.catch((err) => {
toast.error(err);
});
} else {
setPicMessage('Please Select an Image');
toast.error(picMessage);
}
};
And here is the full Profile.js File
import React, { useEffect, useState } from 'react';
import { Button, Col, Container, Form, InputGroup, Row } from 'react-bootstrap';
import { toast, ToastContainer } from 'react-toastify';
import { useDispatch, useSelector } from 'react-redux';
import { getUserDetails, updateUserProfile } from '../actions/userActions';
import { USER_UPDATE_PROFILE_RESET } from '../constant/userConstants';
const Profile = ({ history }) => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [pic, setPic] = useState();
const [password, setPassword] = useState('');
const [picMessage, setPicMessage] = useState();
const [confirmPassword, setConfirmPassword] = useState('');
const [passwordType, setPasswordType] = useState('password');
const [passwordType2, setPasswordType2] = useState('password');
const [showPass, setShowPass] = useState(false);
const [showPass2, setShowPass2] = useState(false);
const dispatch = useDispatch();
const userDetails = useSelector((state) => state.userDetails);
const { user } = userDetails;
// console.log(` this is from line 25 ${user}`);
const userLogin = useSelector((state) => state.userLogin);
const { userInfo } = userLogin;
const userUpdateProfile = useSelector((state) => state.userUpdateProfile);
const { success } = userUpdateProfile;
useEffect(() => {
if (!userInfo) {
history.push('/login');
} else {
if (!user || !user.name || success) {
dispatch({ type: USER_UPDATE_PROFILE_RESET });
dispatch(getUserDetails('profile'));
} else {
setName(user.name);
setEmail(user.email);
setPic(user.pic);
}
}
if (success) {
toast.success('Profile Updated successfully');
}
showPass ? setPasswordType('text') : setPasswordType('password');
showPass2 ? setPasswordType2('text') : setPasswordType2('password');
}, [showPass, showPass2, dispatch, history, success, user, userInfo]);
const postDetails = (pics) => {
setPicMessage(null);
if (pics?.type === 'image/jpeg' || pics?.type === 'image/png') {
const data = new FormData();
data.append('file', pics);
data.append('upload_preset', 'codeblogger_profile_image');
data.append('cloud_name', 'dhuej17x0');
fetch('https://api.cloudinary.com/v1_1/dhuej17x0/image/upload', {
method: 'post',
body: data,
})
.then((res) => res.json())
.then((data) => {
setPic(data.secure_url.toString());
console.log(pic);
})
.catch((err) => {
toast.error(err);
});
} else {
setPicMessage('Please Select an Image');
toast.error(picMessage);
}
};
const submitHandler = (e) => {
e.preventDefault();
if (password !== confirmPassword) {
toast.error('Passwords do not match');
} else {
dispatch(updateUserProfile({ id: user._id, name, email, password }));
}
};
return (
<div className="profilePage mt-4 py-3">
<ToastContainer />
<Container>
<h2>PROFILE</h2>
<Row className="profileContainer">
<Col md={6}>
<Form onSubmit={submitHandler}>
<Form.Group controlId="name" className="mb-2">
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
value={name}
placeholder="Name"
onChange={(e) => setName(e.target.value)}
/>
</Form.Group>
<Form.Group controlId="email" className="mb-2">
<Form.Label>Email</Form.Label>
<Form.Control
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</Form.Group>
<Form.Group controlId="password" className="mb-2">
<Form.Label>New Password</Form.Label>
<InputGroup>
<Form.Control
type={passwordType}
placeholder="New Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<InputGroup.Text>
<i
onClick={() => setShowPass(!showPass)}
className={showPass ? 'fas fa-eye-slash' : 'fas fa-eye'}
style={{ cursor: 'pointer' }}></i>
</InputGroup.Text>
</InputGroup>
</Form.Group>
<Form.Group controlId="confirmPassword" className="mb-2">
<Form.Label>Confirm Password</Form.Label>
<InputGroup>
<Form.Control
type={passwordType2}
placeholder="Confirm Password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
/>
<InputGroup.Text>
<i
onClick={() => setShowPass2(!showPass2)}
className={showPass2 ? 'fas fa-eye-slash' : 'fas fa-eye'}
style={{ cursor: 'pointer' }}></i>
</InputGroup.Text>
</InputGroup>
</Form.Group>
<Form.Group controlId="pic" className="mb-2">
<Form.Label>Change Profile Picture</Form.Label>
<Form.Control
onChange={(e) => postDetails(e.target.files[0])}
type="file"
accept=".jpeg,.png,.jpg"
custom="true"
/>
</Form.Group>
<Button
type="submit"
variant="success"
style={{ letterSpacing: '2px' }}>
UPDATE
</Button>
</Form>
</Col>
<Col
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
<img src={pic} alt={user.name} className="profilePic" />
</Col>
</Row>
</Container>
</div>
);
};
export default Profile;

In submitHandler method, you are not passing pic variable in updateUserProfile.
use this
dispatch(updateUserProfile({ id: user._id, name, email, password, pic }));

Related

my signup page in reactjs is not saving the data to the firebase firestore

in this signup page the user enters username email and password and photo but the user data doesn't store in the firestore firebase. the photo is saving in the storage and the authentication is happening but the user data is not saving in the database.please help
import Helmet from "../components/Helmet/Helmet";
import { Container, Row, Col, Form, FormGroup } from "reactstrap";
import React, { useState } from "react";
import { Link } from "react-router-dom";
import "../styles/login.css";
import { setDoc, doc } from "firebase/firestore";
import { db } from "../firebase.config";
import { useNavigate } from "react-router-dom";
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth";
import { ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";
import { auth } from "../firebase.config";
import { storage } from "../firebase.config";
import { toast } from "react-toastify";
import "../styles/login.css";
const Signup = () => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, Setpassword] = useState("");
const [file, setFile] = useState(null);
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const signup = async (e) => {
e.preventDefault();
setLoading(true);
try {
const userCredential = await createUserWithEmailAndPassword(
auth,
email,
password
);
const user = userCredential.user;
const storageRef = ref(storage, `images/${Date.now() + username}`);
const uploadTask = uploadBytesResumable(storageRef, file);
uploadTask.on(
(error) => {
toast.error(error.message);
},
() => {
getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURl) => {
await updateProfile(user, {
displayName: username,
photoURL: downloadURl,
});
await setDoc(doc(db, "users", user.uid), {
uid: user.uid,
displayName: username,
email,
photoURL: downloadURl,
});
});
}
);
console.log(user);
setLoading(false);
navigate("/login");
toast.success("signup successfull");
} catch (error) {
setLoading(false);
toast.error("something went wrong");
}
};
return (
<Helmet title="Signup">
<section>
<Container>
<Row>
{loading ? (
<Col lg="12" className="text-center">
<h6 className="fw-bold">Loading.....</h6>
</Col>
) : (
<Col lg="6" className="m-auto text-center">
<h3 className="fw-bold fs-4">SignUp</h3>
<Form className="auth__form " onSubmit={signup}>
<FormGroup className="signup__form">
<input
type="text"
placeholder="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</FormGroup>
<FormGroup className="signup__form">
<input
type="email"
placeholder="enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</FormGroup>
<FormGroup className="signup__form">
<input
type="password"
placeholder="enter your password"
value={password}
onChange={(e) => Setpassword(e.target.value)}
/>
</FormGroup>
<FormGroup className="file__group">
<input
type="file"
onChange={(e) => setFile(e.target.file[0])}
/>
</FormGroup>
<button type="submit" className="buy_btn auth__btn">
Create an Account
</button>
<p>
already have an account?
<Link to="/login">Login</Link>
</p>
</Form>
</Col>
)}
</Row>
</Container>
</section>
</Helmet>
);
};
export default Signup;

xhr.js:210 POST http://localhost:3000/api/users/login 401 (Unauthorized)

Hello I am developing a login system and when I try to make a post request to localhost:5000/api/users login I get:
xhr.js:210 POST http://localhost:5000/api/users/login 401 (Unauthorized)
this is my code:
import React, { useState, useEffect} from "react";
import { Form, Button, Row, Col } from "react-bootstrap";
import { Link } from "react-router-dom";
import "./LoginScreen.css";
import axios from 'axios';
function LoginScreen() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const submitHandler = async (e) => {
e.preventDefault();
try {
const config = {
headers: {
"Content-type": "application/json",
},
};
setLoading(true);
const { data } = await axios.post(
"http://localhost:5000/api/users/login",
{
email,
password,
},
config);
console.log(data);
localStorage.setItem("userInfo", JSON.stringify(data));
setLoading(false);
} catch (error) {
setError(error.response.data.message);
console.log(error);
}
};
return (
<div className="login_outer">
<h1>Login Here</h1>
<div className="loginContainer">
<Form onSubmit={ submitHandler }>
<Form.Group controlId="formBasicEmail" >
<Form.Label>E-mail: </Form.Label>
<Form.Control size="lg" type="email" value={email} placeholder="Enter Email" className="input" onChange={(e) => setEmail(e.target.value)}/>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password: </Form.Label>
<Form.Control size="lg" type="password" value={password} placeholder="Enter Password" className="input" onChange={(e) => setPassword(e.target.value)}/>
</Form.Group>
<Button className="login_button" variant="primary" type="submit">
Submit
</Button>
</Form>
<Row className="py-3">
<Col>
New User ? <Link to="/register">Register Here</Link>
</Col>
</Row>
</div>
</div>
);
}
export default LoginScreen;
Can anyone offer help with that ? I also have a proxy in the src folder. If I use postman for that request it does work.

CRUD firestore React function delete()

I am trying to do the delete function for a CRUD with React & Firestore, I already manage to eliminate it, the problem is the way I get the ID since it always deletes the record that is lower in the table.
function delete()
const handleDelete = async(id) =>{
/* setData([]); */
console.log(id)
try {
/* await db.collection('empleado').doc(id).delete(); */
} catch (error) {
console.log(error)
}
}
get ID
useEffect(()=>{
db.collection('empleado')
.onSnapshot((querySnapshot) =>{
querySnapshot.forEach(doc =>{
setData(data => [ ...data,[doc.data().dleted,doc.data().tipoDoc,doc.data().doc,doc.data().lugarExp,doc.data().nombre,doc.data().direccion, doc.data().telefono,doc.data().email,doc.data().cargo,doc.data().rh,doc.data().eps,doc.data().tiempoPago,doc.data().sueldo]]);
});
})
db.collection('empleado').onSnapshot((snapshot)=>{
setId(snapshot.docs.map((doc) => ({id: doc.id})))
})
},[]);
onClick function button parameter
{
name: "Delete",
options: {
filter: true,
sort: false,
empty: true,
customBodyRender: (value, tableMeta, updateValue) => {
return (
<button onClick={ ()=>handleDelete(id) }>
Delete
</button>
);
}
}
},
this is my console.log()
(4) [{…}, {…}, {…}, {…}]
0: {id: "48DIVsf7NLc5ux5vfH76"}
1: {id: "B3Jnpmmtipmi3IwvxKzs"}
2: {id: "cSPnc9lDpgvWNDXsXhfo"}
3: {id: "rLzJuLFfanXTSArA9fd2"}
length: 4
[[Prototype]]: Array(0)
this happen when press button delete (any row button delete), i want upload a image of my table.
Component
import React,{useEffect} from 'react';
import "../../../css/employee.css";
import Dashboard from '../Dashboard';
import { db } from '../../../firebase';
import MUIDataTable from "mui-datatables";
import Form from 'react-bootstrap/Form';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
function Employee(){
const [data,setData] = React.useState([]);
const[id,setId]=React.useState('');
const[dleted,setDleted]=React.useState('');
const handleDelete = async(id) =>{
/* setData([]); */
console.log(id)
try {
/* await db.collection('empleado').doc(id).delete(); */
} catch (error) {
console.log(error)
}
}
useEffect(()=>{
db.collection('empleado')
.onSnapshot((querySnapshot) =>{
querySnapshot.forEach(doc =>{
setData(data => [ ...data,[doc.data().tipoDoc,doc.data().doc,doc.data().lugarExp,doc.data().nombre,doc.data().direccion, doc.data().telefono,doc.data().email,doc.data().cargo,doc.data().rh,doc.data().eps,doc.data().tiempoPago,doc.data().sueldo]]);
});
})
db.collection('empleado').onSnapshot((snapshot)=>{
setId(snapshot.docs.map((doc) => ({id: doc.id, data:doc.data()})))
})
},[]);
const columns =[{
name: "Delete",
options: {
filter: true,
sort: false,
empty: true,
customBodyRender: (value, tableMeta, updateValue) => {
return (
<button onClick={ ()=>handleDelete(id)}>
Delete
</button>
);
}
}
},
"TIPO DOCUMENTO", "DOCUMENTO", "LUGAR EXPEDICION", "NOMBRE","DIRECCION","TELEFONO","EMAIL","CARGO","RH","EPS","TIEMPO SUELDO","SUELDO"];
const options = {
filterType: 'checkbox',
};
return(
<div id="employ">
<div><Dashboard /></div>
<hr/>
<div style={{marginLeft:'18em'}}>
<MUIDataTable
title={"EMPLEADOS"}
data={data}
columns={columns}
options={options}
/>
</div>
</div>
);
}
export default Employee;
Try this:
<button onClick={ ()=>handleDelete(tableMeta.rowData[0])}> //you have to put the index of your id here
Delete
</button>
SOLUCIONADO
COMPONENT Employee
import React,{useEffect} from 'react';
import "../../../css/employee.css";
import Dashboard from '../Dashboard';
import { db } from '../../../firebase';
import MUIDataTable from "mui-datatables";
import Form from 'react-bootstrap/Form';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
function Employee(){
const [data,setData] = React.useState([]);
const[id,setId]=React.useState('');
const[dleted,setDleted]=React.useState('');
const [tipoDoc, setTipoDoc] = React.useState('');
const [doc, setDoc] = React.useState('');
const [lugarExp, setLugarExp] = React.useState('');
const [nombre, setNombre] = React.useState('');
const [direccion, setDireccion] = React.useState('');
const [telefono, setTelefono] = React.useState('');
const [email, setEmail] = React.useState('');
const [cargo, setCargo] = React.useState('');
const [rh, setRh] = React.useState('');
const [eps, setEps] = React.useState('');
const [tiempoPago, setTiempoPago] = React.useState('');
const [sueldo, setSueldo] = React.useState('');
const handleSubmit = async (e) => {
e?.preventDefault();
setData([]);
db.collection("empleado").add({
tipoDoc: tipoDoc,
doc: doc,
lugarExp: lugarExp,
nombre: nombre,
direccion: direccion,
telefono: telefono,
email: email,
cargo: cargo,
rh:rh,
eps:eps,
tiempoPago:tiempoPago,
sueldo:sueldo,
}).then(() => {
}).catch((error) => {
alert(error.message)
});
}
const handleDelete = async(id,index) =>{
setData([]);
let parse = '';
let parse2='';
console.log(id);
console.log(index);
parse = parseInt(index);
for (let i = 0; i < id.length; i++) {
if(i === parse ){
const element = id[i];
console.log("element",typeof(element))
parse2 = element;
console.log("B3Jnpmmtipmi3IwvxKzs"==parse2)
await db.collection("empleado").doc(parse2).delete().then(() => {
console.log("Document successfully deleted!");
}).catch((error) => {
console.error("Error removing document: ", error);
});
}
}
}
useEffect(()=>{
db.collection('empleado')
.onSnapshot((querySnapshot) =>{
querySnapshot.forEach(doc =>{
setData(data => [ ...data,[doc.data().tipoDoc,doc.data().doc,doc.data().lugarExp,doc.data().nombre,doc.data().direccion, doc.data().telefono,doc.data().email,doc.data().cargo,doc.data().rh,doc.data().eps,doc.data().tiempoPago,doc.data().sueldo]]);
});
})
db.collection('empleado').onSnapshot((snapshot)=>{
setId(snapshot.docs.map((doc) => (doc.id)))
})
},[]);
const columns =[{
name: "Delete",
options: {
filter: true,
sort: false,
empty: true,
customBodyRender: (value, tableMeta, updateValue) => {
return (
<button onClick={ ()=>handleDelete(id,`${tableMeta.rowIndex}`)}>
Delete
</button>
);
}
}
},
, "TIPO DOCUMENTO", "DOCUMENTO", "LUGAR EXPEDICION", "NOMBRE","DIRECCION","TELEFONO","EMAIL","CARGO","RH","EPS","TIEMPO SUELDO","SUELDO"];
const options = {
filterType: 'checkbox',
};
return(
<div id="employ">
<div><Dashboard /></div>
<hr/>
<div style={{marginLeft:'18em'}}>
<MUIDataTable
title={"EMPLEADOS"}
data={data}
columns={columns}
options={options}
/>
</div>
<hr />
<hr /><br /><br /><br/>
<Form id="form-contact">
<Row className="mb-3">
<Form.Group as={Col} controlId="formGridState">
<Form.Label>Tipo documento</Form.Label>
<Form.Select defaultValue="-" value={tipoDoc} onChange={e => { setTipoDoc(e.target.value) }}>
<option>-</option>
<option>Tarjeta Identidad</option>
<option>Cedula Ciudadania</option>
<option>Cedula Extranjeria</option>
</Form.Select>
</Form.Group>
<Form.Group as={Col} controlId="formGridEmail">
<Form.Label>Documento</Form.Label>
<Form.Control type="text" value={doc} onChange={e => { setDoc(e.target.value) }} placeholder="0000000" />
</Form.Group>
<Form.Group as={Col} controlId="formGridPassword">
<Form.Label>Lugar expedicion</Form.Label>
<Form.Control type="text" value={lugarExp} onChange={e => { setLugarExp(e.target.value) }} placeholder="municipio/departamento" />
</Form.Group>
</Row>
<Form.Group className="mb-3" controlId="formGridAddress1">
<Form.Label>Nombre</Form.Label>
<Form.Control type="text" placeholder="name" value={nombre} onChange={e => { setNombre(e.target.value) }} />
</Form.Group>
<Form.Group className="mb-3" controlId="formGridAddress2">
<Form.Label>Direccion</Form.Label>
<Form.Control placeholder="Cra - #" value={direccion} onChange={e => { setDireccion(e.target.value) }} />
</Form.Group>
<Row className="mb-3">
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>Telefono </Form.Label>
<Form.Control value={telefono} onChange={e => { setTelefono(e.target.value) }} />
</Form.Group>
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>Email </Form.Label>
<Form.Control value={email} onChange={e => { setEmail(e.target.value) }} />
</Form.Group>
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>Cargo </Form.Label>
<Form.Control value={cargo} onChange={e => { setCargo(e.target.value) }} />
</Form.Group>
<Form.Group as={Col} controlId="formGridState">
<Form.Label>RH</Form.Label>
<Form.Select defaultValue="-" value={rh} onChange={e => { setRh(e.target.value) }}>
<option>-</option>
<option>A+</option>
<option>AB+</option>
<option>O+</option>
</Form.Select>
</Form.Group>
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>EPS </Form.Label>
<Form.Control value={eps} onChange={e => { setEps(e.target.value) }} />
</Form.Group>
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>Tiempo pago </Form.Label>
<Form.Control value={tiempoPago} onChange={e => { setTiempoPago(e.target.value) }} />
</Form.Group>
<Form.Group as={Col} controlId="formGridCity">
<Form.Label>Sueldo </Form.Label>
<Form.Control value={sueldo} onChange={e => { setSueldo(e.target.value) }} />
</Form.Group>
</Row>
<Form.Group className="mb-3" id="formGridCheckbox" style={{textAlign:'left'}}>
<Form.Check type="checkbox" label="Acepto términos del servicio y tratamiento de datos." />
</Form.Group>
<button type="button" class="btn btn-secondary btn-lg" onClick={()=>handleSubmit()} >Agregar</button>
</Form>
<hr/>
<hr/>
</div>
);
}
export default Employee;

How to fix memory leak in react?

const Register = () => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [passConf, setPassConf] = useState("");
const [errors, setErrors] = useState([]);
const [loading, setLoading] = useState(false);
const [usersRef, setUsersRef] = useState(null);
const isPasswordValid = () => {
if (password.length < 6 || passConf.length < 6) {
return false;
} else if (password !== passConf) {
return false;
} else {
return true;
}
};
const isFormValid = () => {
let errors = [];
let error;
if (!isPasswordValid()) {
error = { message: "Password is invalid" };
setErrors(errors.concat(error));
return false;
} else {
return true;
}
};
const saveUser = (createdUser) => {
setUsersRef(firebase.database().ref("users"));
return usersRef.child(createdUser.user.uid).set({
name: createdUser.user.displayName,
avatar: createdUser.user.photoURL,
});
};
const handleSubmit = (event) => {
event.preventDefault();
if (isFormValid()) {
setErrors([]);
setLoading(true);
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((createdUser) => {
console.log(createdUser);
createdUser.user
.updateProfile({
displayName: username,
photoURL: `https://gravatar.com/avatar/${md5(
createdUser.user.email
)}?d=identicon`,
})
.then(() => {
saveUser(createdUser).then(() => {
console.log("user saved");
setLoading(false);
});
})
.catch((err) => {
setLoading(false);
setErrors(errors.concat(err));
});
})
.catch((err) => {
setLoading(false);
setErrors(errors.concat(err));
});
}
};
const displayErrors = (errors) =>
errors.map((error, i) => <p key={i}>{error.message}</p>);
return (
<Grid textAlign="center" verticalAlign="middle" className="app">
<Grid.Column style={{ maxWidth: 450 }}>
<Header as="h2" icon color="orange" textAlign="center">
<Icon name="rocketchat" color="orange" />
Register for Super Chat
</Header>
<Form onSubmit={handleSubmit} size="large">
<Segment stacked>
<Form.Input
fluid
name="username"
icon="user"
iconPosition="left"
type="text"
placeholder="Username"
value={username}
required
onChange={(e) => setUsername(e.target.value)}
/>
<Form.Input
fluid
name="email"
icon="mail"
iconPosition="left"
type="email"
placeholder="Email"
value={email}
required
onChange={(e) => setEmail(e.target.value)}
/>
<Form.Input
fluid
name="password"
icon="lock"
iconPosition="left"
type="password"
placeholder="Password"
value={password}
required
onChange={(e) => setPassword(e.target.value)}
/>
<Form.Input
fluid
name="passConf"
icon="repeat"
iconPosition="left"
type="password"
placeholder="Password Confirmation"
value={passConf}
required
onChange={(e) => setPassConf(e.target.value)}
/>
<Button disabled={loading} color="orange" fluid size="large">
Submit
</Button>
</Segment>
</Form>
{errors.length ? (
<Message error>
<h3>Error</h3>
{displayErrors(errors)}
</Message>
) : null}
<Message>
Already a user? <Link to="/login">Login</Link>
</Message>
</Grid.Column>
</Grid>
);
};
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
I am not able to find where this memory leak is happening.
I am able to sign in with one account but after signing out and signing in again with another account, it's giving this warninng and firebase realtime database is also not updating.
How can I fix memory leak here?

How to change value in input element? (reactjs)

What I'm trying to do is that if user click on button 'Edit', modal is opened, and in value of input fields should be old, not updated value. But when I do that, I can't write anything else.
(eg. if user wants to update name, by opening modal EditUser, the old value of users name should be there, in input filed, and user needs to have opportunity to change that.)
<Input
type="text"
onChange={(e: any) => setFirstNameUpdated(e.target.value)}
value={props.userInfo.firstName}>
</Input>
i tried to use useRef:
const inputNameRef = useRef<HTMLInputElement | any>(null)
useEffect(() => {
console.log(inputNameRef.current) // this is null
console.log(props.userInfo.firstName) // this is OK
inputNameRef.current && (inputNameRef.current.value=props.userInfo.firstName)
}, [])
<Input
type="text"
onChange={(e: any) => setFirstNameUpdated(e.target.value)}
ref={inputNameRef}>
</Input>
EDIT:
SinglePost.tsx
import React, { useState, useRef, useEffect } from 'react'
import { Modal, ModalHeader, ModalBody, ModalFooter, Button, FormGroup, Label, Input } from 'reactstrap'
import Axios from 'axios'
import '../user_profile/myprofile.css'
function UpdateProfile(props: any) {
const [firstNameUpdated, setFirstNameUpdated] = useState('')
const [lastNameUpdated, setLastNameUpdated] = useState('')
const [userBioUpdated, setUserBioUpdated] = useState('')
const inputNameRef = useRef<HTMLInputElement | any>(null)
useEffect(() => {
console.log(inputNameRef.current, props.userInfo.firstName)
inputNameRef.current && (inputNameRef.current.value = props.userInfo.firstName)
}, [])
// upload image
const [file, setFile] = useState('')
const [uploaded, setUploaded] = useState('')
const handleImageUpload = (e: any) => {
e.preventDefault();
setFile(e.target.files[0])
};
const onClickHandler = (e: any) => {
const formData = new FormData()
formData.append('fileImage', file)
Axios.post("/api/image", formData, {})
.then(res => {
//console.log(`UPLOADED: http://localhost:5000/${res.data.fileImage}`)
setUploaded(`http://localhost:5000/${res.data.fileImage}`)
})
.catch(err => console.log(err))
}
// update user
const updateUser = (e: any) => {
e.preventDefault()
props.setIsEditOpen(false)
const formData = new FormData()
formData.append('fileImage', file)
formData.append('first_name', firstNameUpdated)
formData.append('last_name', lastNameUpdated)
formData.append('user_bio', userBioUpdated)
const config: any = { header: { "Content-Type": "multipart/form-data" } }
Axios
.put(`/api/users/${props.userID}`, formData, config)
.then(res => {
const user = res.data
props.setUserInfo({
firstName: user.first_name,
lastName: user.last_name,
userBio: user.user_bio,
userPhoto: user.profile_image
})
})
.catch(err => console.log(err))
}
return (
<div>
{props.isEditOpen &&
<Modal isOpen={props.isEditOpen} toggle={() => props.setIsEditOpen(!props.isEditOpen)} backdrop="static">
<ModalHeader>Update your profile</ModalHeader>
<ModalBody>
<FormGroup>
<Label>Profile Image</Label>
<Input type="file" name="fileImage" onChange={handleImageUpload}></Input>
</FormGroup>
<Button onClick={onClickHandler} className="btn-upload-img">Upload file</Button>
<div className="inline">
{uploaded ? <img src={uploaded} style={{ width: "100px" }}></img> : <img src={props.userInfo.userPhoto} style={{ width: "100px" }}></img>}
</div>
<FormGroup>
<Label>First Name</Label>
<Input type="text" onChange={(e: any) => setFirstNameUpdated(e.target.value)} ref={inputNameRef} value={firstNameUpdated}></Input>
</FormGroup>
<FormGroup>
<Label>Last Name</Label>
<Input type="text" onChange={(e: any) => setLastNameUpdated(e.target.value)} defaultValue={props.userInfo.lastName}></Input>
</FormGroup>
<FormGroup>
<Label>About me</Label>
<Input type="text" onChange={(e: any) => setUserBioUpdated(e.target.value)} defaultValue={props.userInfo.userBio}></Input>
</FormGroup>
</ModalBody>
<ModalFooter>
<Button color="success" onClick={updateUser} className="btn-update">Update</Button>
<Button color="danger" onClick={() => props.setIsEditOpen(false)}>Cancel</Button>
</ModalFooter>
</Modal>}
</div>
)
}
export default UpdateProfile
MyProfile.tsx
import React, { useState, useEffect, useContext } from 'react'
import './myprofile.css'
import Axios from 'axios'
import SinglePost from '../single_post/SinglePost'
import { AppContext } from '../context/AppContext'
import UpdateProfile from '../modals/UpdateProfile'
function MyProfile() {
const [userInfo, setUserInfo] = useState({
firstName: '',
lastName: '',
userBio: 'Write something about yourself.',
userPhoto: ''
})
const [isEditOpen, setIsEditOpen] = useState(false)
const { userID, setUserID } = useContext(AppContext)
// open modal on click 'edit'
const editUser = () => {
setIsEditOpen(true)
}
// get user data
const storedToken = localStorage.getItem('token')
useEffect(() => {
const config = {
headers: { "x-auth-token": `${storedToken}` }
}
Axios
.get('/api/auth/user', config)
.then(res => {
console.log('response', res)
const user = res.data.user
setUserID(user._id)
setUserInfo({
firstName: user.first_name,
lastName: user.last_name,
userBio: user.user_bio,
userPhoto: user.profile_image
})
})
.catch(err => console.log(err))
}, [])
return (
<div className="profile-container">
<button className="btn-edit" onClick={editUser}>
<i className="fa fa-edit"></i>
</button>
<div className="user-info">
<div className="img-circular">
<img className="user-profile-img2" src={userInfo.userPhoto}></img>
</div>
<p className="user-name">{userInfo.firstName} {userInfo.lastName}</p>
<p className="about-user">{userInfo.userBio}</p>
</div>
<div className="user-posts">
<p className="my-posts-title">My Posts</p>
</div>
{isEditOpen && <UpdateProfile
userID={userID}
setIsEditOpen={setIsEditOpen}
isEditOpen={isEditOpen}
setUserInfo={setUserInfo}
userInfo={userInfo}
/>}
{/* <SinglePost /> */}
</div>
)
}
export default MyProfile

Resources