I am getting stack trace error and can't resolve it - reactjs

I am getting the following error and i cant figure out what do to.
Uncaught Error: The error you provided does not contain a stack trace.
at L (index.js:1)
at Y (index.js:1)
at index.js:1
at index.js:1
at o (index.js:1)
import React, { useState, useEffect } from "react";
import "./App.css";
import Post from "./Post";
import { db, auth } from "./firebase";
import { Button, Modal, Input } from "#material-ui/core";
import { makeStyles } from "#material-ui/core/styles";
function getModalStyle() {
const top = 50;
const left = 50;
return {
top: `${top}%`,
left: `${left}%`,
transform: `translate(-${top}%, -${left}%)`,
};
}
const useStyles = makeStyles((theme) => ({
paper: {
position: "absolute",
width: 400,
backgroundColor: theme.palette.background.paper,
border: "2px solid #000",
boxShadow: theme.shadows[5],
padding: theme.spacing(2, 4, 3),
},
}));
function App() {
const classes = useStyles();
const [modalStyle] = React.useState(getModalStyle);
const [posts, setPosts] = useState([]);
const [open, setOpen] = useState(false);
const [username, setUsername] = useState();
const [password, setPassword] = useState();
const [email, setEmail] = useState();
useEffect(() => {
db.collection("posts").onSnapshot((snapshot) => {
setPosts(snapshot.docs.map((doc) => ({ id: doc.id, post: doc.data() })));
});
}, []);
const signUp = (e) => {
e.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.catch((error) => alert(error.message));
};
return (
// header
<div className="app">
<Modal open={open} onClose={() => setOpen(false)}>
<div style={modalStyle} className={classes.paper}>
<form action="" className="app-signup">
<center>
<img
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png"
alt="instagram"
className="app-headerImage"
/>
</center>
<Input
type="text"
placeholder="userName"
value={username}
onChange={(e) =>
setUsername(e.target.value)}
/>
<Input
type="text"
placeholder="email"
value={email}
onChange={(e) =>
setEmail(e.target.value)}
/>
<Input
type="password"
placeholder="password"
value={password}
onChange={(e) =>
setPassword(e.target.value)}
/>
<Button onClick=
{signUp}>signUp</Button>
</form>
</div>
</Modal>
<div className="app-header">
<img
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png"
alt="instagram"
className="app-headerImage"
/>
</div>
<Button onClick={() =>
setOpen(true)}>Signup</Button>
{posts.map(({ post, id }) => {
const { userName, caption, imageUrl } = post;
return (
<Post
key={id}
userName={userName}
caption={caption}
imageUrl={imageUrl}
/>
);
})}
</div>
//posts
//posts
);
}
export default App;

Related

My react typescript code does not render data from child to parent component in one go

interface Props {
handleNext2: () => void;
handleprevious2: () => void;
visible2: boolean;
onFinish: (values: any) => void;
}
const userRef = useRef<HTMLInputElement>();
const [moNumber, setMoNumber] = useState<string>("");
const [validMoNumber, setValidMoNumber] = useState<boolean>(false);
const [moNumberW, setMoNumberW] = useState<string>("");
const [validdMoNumberW, setValiddMoNumberW] = useState<boolean>(false);
const [lLine, setLline] = useState<string>("");
const [validLline, setValidLline] = useState<boolean>(false);
const [email, setEmail] = useState<string>("");
const [web, setWeb] = useState<string>("");
useEffect(() => {
userRef.current?.focus();
}, []);
useEffect(() => {
const result: boolean = MNO.test(moNumber);
setValidMoNumber(result);
}, [moNumber]);
useEffect(() => {
const result: boolean = MNOW.test(moNumberW);
setValiddMoNumberW(result);
}, [moNumberW]);
useEffect(() => {
const result = L_LINE.test(lLine);
setValidLline(result);
}, [lLine]);
return (
<Modal
title="Sign Up"
open={visible2}
cancelButtonProps={{ style: { display: "none" } }}
okButtonProps={{ style: { display: "none" } }}
// onOk={handleNext2}
// okText="Next"
// onCancel={handleprevious2}
// cancelText="Previous"
>
<div className="header">
<h1>Contact Information</h1>
<div className="text-container">
<p className="text-1">
This Information is what your prospective clients will be using to
get in touch with you. Make sure its accurate
</p>
</div>
<h2>"Greate coaches prioratize communication"</h2>
</div>
<Form
className="form"
form={form2}
name="contact"
onFinish={handleFinish2}
>
<div className="input-controller">
<div className="input-with-label">
<h3>Mobile No</h3>
<Form.Item
className="form-item"
name="moNo"
hasFeedback
rules={[
{
// required: true,
message: "Please input your mobile no",
},
{
validator: (_, value) => {
if (!validMoNumber && value) {
return Promise.reject("Invalid mobile no");
}
if (!value) {
return Promise.resolve();
}
return Promise.resolve();
},
},
]}
>
<Input
className="inputs"
ref={userRef as any}
value={moNumber}
onChange={(e) => {
setMoNumber(e.target.value);
}}
/>
</Form.Item>
</div>
<div className="input-with-label">
<h3>WhatssApp NO</h3>
<Form.Item
className="form-item"
name="WhatsApp"
hasFeedback
rules={[
{
validator: (_, value) => {
if (!validdMoNumberW && value) {
return Promise.reject("Invalid last name");
}
if (!value) {
return Promise.resolve();
}
return Promise.resolve();
},
},
]}
>
<Input
value={moNumberW}
className="inputs"
onChange={(e) => {
setMoNumberW(e.target.value);
}}
/>
</Form.Item>
</div>
</div>
<div className="input-controller">
<div className="input-with-label">
<h3>LandLine</h3>
<Form.Item
className="form-item"
name="LandLine"
rules={[
{
validator: (_, value) => {
if (!validLline && value) {
return Promise.reject("Invalid password");
}
if (!value) {
return Promise.resolve();
}
return Promise.resolve();
},
},
]}
hasFeedback
>
<Input
onChange={(e) => setLline(e.target.value)}
className="inputs"
value={lLine}
/>
</Form.Item>
</div>
<div className="input-with-label">
<h3>E-mail</h3>
<Form.Item
className="form-item"
name="Email"
rules={[
{
type: "email",
message: "The input is not valid E-mail!",
},
{
// required: true,
message: "Please input your E-mail!",
},
]}
>
<Input
className="inputs"
onChange={(e) => setEmail(e.target.value)}
value={email}
/>
</Form.Item>
</div>
</div>
<h3>Website</h3>
<Form.Item className="form-item" name="Website" hasFeedback>
<Input
className="inputs"
id="website"
onChange={(e) => setWeb(e.target.value)}
value={web}
/>
</Form.Item>
<Form.Item>
<Button style={{ width: "100%" }} type="primary" htmlType="submit">
Next
</Button>
</Form.Item>
<Form.Item>
<Button
style={{ width: "100%", backgroundColor: "red" }}
type="primary"
onClick={handleprevious2}
>
Cancel
</Button>
</Form.Item>
</Form>
</Modal>
);
};
export default PopUp2;
I use above code as a child component.onFinishFunction is used to send data to the parent.
This is a parent.
onst HeadCoachSignUp: React.FC = () => {
const [form] = Form.useForm();
// ---------------------------To send data------------------------------
//-------For all signup data-------------------------
const [firstName, setFName] = useState<string>("");
const [lastName, setLName] = useState<string>("");
const [pwd, setPwd] = useState<string>("");
const [address, setAddress] = useState<string>("");
const [nicNumber, setNicNo] = useState<string>("");
const [Gender, setGender] = useState<string>("");
const [moNumber, setMoNumber] = useState<string>("");
const [moNumberWhatsApp, setMoNumberW] = useState<string>("");
const [landLine, setLline] = useState<string>("");
const [Email, setEmail] = useState<string>("");
const [webSite, setWeb] = useState<string>("");
const [formData1, setFormData1] = useState<FormData | any>({});
const [formData2, setFormData2] = useState<FormData | any>({});
const [certificates, setCertificates] = useState<FormData | any>({});
const [Athletics, setAthletics] = useState<FormData | any>({});
const [experiences, setExperiences] = useState<FormData | any>({});
const [formData6, setFormData6] = useState<FormData | any>({});
const [formData7, setFormData7] = useState<FormData | any>({});
const [formData8, setFormData8] = useState<FormData | any>({});
const handleFormFinish1 = (values: any) => {
setFormData1(values);
};
const handleFormFinish2 = (values: any) => {
setFormData2(values);
console.log(moNumber, moNumberWhatsApp, landLine, Email, webSite);
axios
.post("http://localhost:5001/api/headcoach/signup", {
moNumber: moNumber,
moNumberW: moNumberWhatsApp,
lLine: landLine,
email: Email,
webSite: webSite,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error, error.response);
});
};
useEffect(() => {
const { fName, lName, password, Address, nicNo, gender } = formData1;
const { moNo, WhatsApp, LandLine, Email, Website } = formData2;
const { des2 } = formData6;
const { sbscribe } = formData8;
setFName(fName);
setLName(lName);
setPwd(password);
setAddress(Address);
setNicNo(nicNo);
setGender(gender);
setMoNumber(moNo);
setMoNumberW(WhatsApp);
setLline(LandLine);
setEmail(Email);
setWeb(Website);
setPackageDescription(formData6);
// setRate1(rate1);
// setRate2(rate2);
// setMinONumber1(minONumber1);
// setMinONumber2(minONumber2);
// setDiscount1(discount1);
// setDiscount2(discount2);
// setFrom1(from1);
// setTo1(to1);
// setFrom2(from2);
// setTo2(to2);
// setDes1(des1);
// setDes2(des2);
setSubscribe(sbscribe);
});
const handleNext2 = () => {
form
.validateFields()
.then(() => {
form.resetFields();
setVisible2(!visible2);
setVisible3(!visible3);
})
.catch((info) => {
console.log("Validate Failed:", info);
});
};
return (
<div
style={{
display: "flex",
justifyContent: "center",
marginTop: "20%",
}}
>
{/* <Test /> */}
<Button type="primary" onClick={showModal}>
SignUp
</Button>
<PopUp1
handleNext1={handleNext1}
handleCancel1={handleCancel1}
visible1={visible1}
onFinish={handleFormFinish1}
/>
<PopUp2
onFinish={handleFormFinish2}
handleNext2={handleNext2}
handleprevious2={handleprevious2}
visible2={visible2}
/>
<PopUp3
visible3={visible3}
handleNext3={handleNext3}
handleprevious3={handleprevious3}
onFinish={handleFormFinish3}
/>
<PopUp4
visible4={visible4}
handleNext4={handleNext4}
handleprevious4={handleprevious4}
onFinish={handleFormFinish4}
/>
<PopUp5
visible5={visible5}
handleNext5={handleNext5}
handleprevious5={handleprevious5}
onFinish={handleFormFinish5}
/>
<PopUp6
visible6={visible6}
handleNext6={handleNext6}
handleprevious6={handleprevious6}
onFinish={handleFormFinish6}
/>
<PopUp7
visible7={visible7}
handleNext7={handleNext7}
handleprevious7={handleprevious7}
/>
<PopUp8
visible8={visible8}
handleFinish={handleFinish}
handleprevious8={handleprevious8}
onFinish={handleFormFinish8}
/>
</div>
);
};
export default HeadCoachSignUp;
. This is a full code. But I reduced some parts. So please give me a solution to take data from the child to parent component. When I submit the form, It will not be updated in the parent. It prints values as undefined. If again submit the same form with same data as second submit, It will take the data to parent and sends to console, why is that?

Why is my onSubmit not working in PrimeReact Dialog?

My code is no longer submitting data when onSubmit is pushed even though it was when I was using a and tag:
<Modal><Form onSubmit={ saveProject }></Form></Modal>
The only thing different now is I substituted Modal for as I am using PrimeReact and deleted the tag. Now it's no longer submitting data.
Can anyone tell me why it is no longer submitting the data to the backend?
/Projects.js
import React, { useState, useEffect } from "react";
import { Column } from "primereact/column";
import { DataTable } from "primereact/datatable";
import { Button } from "primereact/button";
// import { Modal, ModalFooter, ModalHeader } from "react-bootstrap";
import { InputText } from "primereact/inputtext";
import { InputTextarea } from "primereact/inputtextarea";
// import { InputNumber } from "primereact/inputnumber";
import { Dropdown } from "primereact/dropdown";
import { Dialog } from "primereact/dialog";
import axios from "axios";
const Projectz = () => {
const [ticket_title, setTicketTitle] = useState("");
const [ticket_description, setTicketDescription] = useState("");
// const [time_takes, setTimeTakes] = useState("");
const [type_menu, setTypeMenu] = useState("");
const [priority_menu, setPriorityMenu] = useState("");
const [status_menu, setStatusMenu] = useState("");
const [projects, setProjects] = useState([]);
//part of modal
const [displayResponsive, setDisplayResponsive] = useState(false);
// const [position, setPosition] = useState("center");
useEffect(() => {
getProjects();
}, []);
const getProjects = async () => {
const response = await axios.get("http://localhost:5002/ticket_table");
setProjects(response.data);
};
const saveProject = async (e) => {
e.preventDefault();
await axios.post("http://localhost:5002/ticket_table", {
ticket_title: ticket_title,
ticket_description: ticket_description,
// time_takes: time_takes,
type_menu: type_menu,
priority_menu: priority_menu,
status_menu: status_menu,
});
};
const dropdownValues1 = [{ value: "Issue" }, { value: "Bug" }, { value: "Error" }, { value: "Other" }];
const dropdownValues2 = [{ value: "Low" }, { value: "Medium" }, { value: "High" }, { value: "Immediate" }];
const dropdownValues3 = [{ value: "New" }, { value: "Open" }, { value: "In Progress" }, { value: "Resolved" }, { value: "Additional Info Required" }];
const dialogFuncMap = {
displayResponsive: setDisplayResponsive,
};
const onClick = (name, position) => {
dialogFuncMap[`${name}`](true);
};
const onHide = (name) => {
dialogFuncMap[`${name}`](false);
};
const renderFooter = (name) => {
return (
<div>
<Button label="Submit" className="p-button-rounded p-button-success mr-2 mb-2 success" />
</div>
);
};
// const [show, setShow] = useState(false);
// const handleClose = () => setShow(false);
// const handleShow = () => setShow(true);
return (
<>
<div className="grid table-demo">
<div className="col-12">
<div className="card">
<h5>Tickets</h5>
<div>
{/* <Button label="New Ticket" className="p-button-rounded mr-2 mb-2 npbutton" onClick={handleShow} /> */}
<Button className="p-button-rounded mr-2 mb-2 npbutton" label="New Ticket" onClick={() => onClick("displayResponsive")} />
</div>
<Dialog className="dialogModal" header="Create Ticket" visible={displayResponsive} onHide={() => onHide("displayResponsive")} breakpoints={{ "960px": "75vw" }} style={{ width: "30vw" }} footer={renderFooter("displayResponsive")}>
<form onSubmit={saveProject}>
<h5>Ticket Name</h5>
<InputText value={ticket_title} onChange={(e) => setTicketTitle(e.target.value)} type="text" placeholder="Enter ticket name"></InputText>
<h5>Ticket Description</h5>
<InputTextarea value={ticket_description} onChange={(e) => setTicketDescription(e.target.value)} type="text" placeholder="Enter ticket description" autoResize rows="3" cols="30" />
{/* <h5>Time Estimate (Hours)</h5> */}
{/* <InputNumber value={time_takes} onValueChange={(e) => setTimeTakes(e.value)} showButtons mode="decimal"></InputNumber> */}
<h5>Type</h5>
<Dropdown value={type_menu} onChange={(e) => setTypeMenu(e.value)} options={dropdownValues1} optionLabel="value" placeholder="Select" />
<h5>Priority</h5>
<Dropdown value={priority_menu} onChange={(e) => setPriorityMenu(e.value)} options={dropdownValues2} optionLabel="value" placeholder="Select" />
<h5>Status</h5>
<Dropdown value={status_menu} onChange={(e) => setStatusMenu(e.value)} options={dropdownValues3} optionLabel="value" placeholder="Select" />
</form>
</Dialog>
<div>
<DataTable
// sortMode="single" sortField="representative.name"
sortOrder={1}
scrollable
scrollHeight="400px"
responsiveLayout="scroll"
>
<Column field="ticket_title" header="Ticket Title" style={{ minWidth: "200px" }}></Column>
<Column field="description" header="Description" style={{ minWidth: "350px" }}></Column>
<Column field="status" header="Status" style={{ minWidth: "200" }}></Column>
<Column field="createdAt" header="Date" style={{ minWidth: "200px" }}></Column>
</DataTable>
</div>
</div>
</div>
</div>
<div className="grid table-demo">
<div className="col-12">
<div className="card">
<h5>Ticket Info</h5>
<div>
<DataTable
// value={projects}
// sortMode="single" sortField="representative.name"
// sortOrder={1}
// scrollable
// scrollHeight="400px"
// responsiveLayout="scroll"
>
{projects.map((project, index) => (
<tr key={project.id}>
<td>{index + 1}</td>
<td>{project.ticket_title}</td>
<td>{project.ticket_description}</td>
{/* <td>{ticket.time_takes}</td> */}
<td>{project.type_menu}</td>
<td>{project.priority_menu}</td>
<td>{project.status_menu}</td>
</tr>
))}
</DataTable>
</div>
</div>
</div>
</div>
</>
);
};
export default React.memo(Projectz);
This is because the Dialog renders renderFooter outside of your <form>. I ran into the same issue.
You can fix it instead of using the footer just rendering your button to look like its in the footer.
<Dialog className="dialogModal" header="Create Ticket" visible={displayResponsive} onHide={() => onHide("displayResponsive")} breakpoints={{ "960px": "75vw" }} style={{ width: "30vw" }}>
<form onSubmit={saveProject}>
....
<div className="p-dialog-footer pb-0">
<Button label="Submit" type="submit" className="p-button-rounded p-button-success mr-2 mb-2" />
</div>
</form>
</Dialog>

Can't update the profile picture using cloudinary

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 }));

In react, some keywords not defined but I think I defined them [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I practicing React to clone Instagram. In App.js, I tried to track email and password so I make input part that received email and password, and here
const [password, setPassword] = useState("");
const [email, setEmail] = useState("");
auth
.createUserWithEmailAndPassword(email, password)
.catch((error) => alert(error.message));
<Input
placeholder="username"
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<Input
placeholder="username"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Button type="submit" onClick={signUp}>
It should be read my email and password as a state but it did't work...
Could you help me with it? I am so sorry if I ask a stupid question. I am just getting started learning to react only 3 weeks.
Just in case, I will leave a whole code below
import "./App.css";
import Post from "./Post";
import React, { useState, useEffect } from "react";
import { db, auth } from "./firebase";
// Basic Modal
import Modal from "#mui/material/Modal";
// import { makeStyles } from "#mui/material";
// import { makeStyles } from "#mui/styles";
import { makeStyles } from "#material-ui/core/styles";
import { Button, Input } from "#material-ui/core";
function getModalStyle() {
const top = 50;
const left = 50;
return {
top: `${top}%`,
left: `${left}%`,
transform: `translate(-${top}%, -${left}%)`,
};
}
const useStyles = makeStyles((theme) => ({
paper: {
position: "absolute",
width: 400,
backgroundColor: theme.palette.background.paper,
border: "2px solid #000",
boxShadow: theme.shadows[5],
padding: theme.spacing(2, 4, 3),
},
}));
const signUp = (event) => {
// This is to prevent the page from refreshing when we submit the form
event.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.catch((error) => alert(error.message));
};
function App() {
const classes = useStyles();
const [modalStyle] = useState(getModalStyle);
const [posts, setPosts] = useState([]);
const [open, setOpen] = useState(false);
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [email, setEmail] = useState("");
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((authUser) => {
if (authUser) {
//user has logged in
console.log(authUser);
setUser(authUser);
if (authUser.displayName) {
// don't updatee username
} else {
//if we just created someone
return authUser.updateProfile({
displayName: username,
});
}
} else {
//user has logged out
setUser(null);
}
});
return () => {
//perform some cleanup actions
unsubscribe();
};
}, [user, username]);
// USEEFFECT Runs a piece of code based on a speicific condition
useEffect(() => {
//this is where the code run
db.collection("posts").onSnapshot((snapshot) => {
//every time a new post is added, this code fired
setPosts(
snapshot.docs.map((doc) => ({
id: doc.id,
post: doc.data(),
}))
);
});
}, []);
return (
<div className="app">
{/* <Button onClick={handleOpen}>Open modal</Button> */}
<Modal open={open} onClose={() => setOpen(false)}>
<div style={modalStyle} className={classes.paper}>
<form className="app__signup">
<center>
<img
className="app__headerImage"
height="40px;"
src="https://toogreen.ca/instagreen/img/instagreen.svg"
alt=""
/>
</center>
<Input
type="text"
placeholder="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<Input
placeholder="username"
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<Input
placeholder="username"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Button type="submit" onClick={signUp}>
Sign Up
</Button>
</form>
</div>
</Modal>
<div className="app__header">
<div className="app__headerLogo">
<span>Westagram</span>
</div>
</div>
<Button onClick={() => setOpen(true)}>Sign Up</Button>
<h1>
Hello Clever Programmers Let's build an Instagram Clone with React!
</h1>
{posts.map(({ id, post }) => (
<Post
key={id}
username={post.username}
caption={post.caption}
imageUrl={post.imageUrl}
/>
))}
</div>
);
}
export default App;
It is great that you are learning React yourself. Keep learning!
I will not get you the whole answer to not prevent you from finding the answer yourself, it is the best way to learn, and finding your own solution is a great feeling :)
Instead, I give you a hint and a book: signUp function is not correct.
const signUp = (event) => {
event.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.catch((error) => alert(error.message));
};
There are no email and password variables in the scope of the function.
This topic explains what is the Scope and I believe it will help you to fix your code.

How do I make the invalid hook call go away?

I get this error when trying to npm start my project:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
import React, { useState, useEffect } from 'react';
import './index.css';
import conspireLogo from './conspireLogo.png';
import Post from './Post'
import { auth, db } from './firebase';
import { makeStyles } from '#material-ui/core/styles';
import Modal from '#material-ui/core/Modal';
import { Button, Input } from '#material-ui/core'
import ImageUpload from './imageUpload';
//import { BrowserRouter, Route, Switch } from 'react-router-dom';
function getModalStyle() {
const top = 50;
const left = 50;
return {
top: `${top}%`,
left: `${left}%`,
transform: `translate(-${top}%, -${left}%)`,
};
}
const useStyles = makeStyles((theme) => ({
paper: {
position: 'absolute',
width: 400,
backgroundColor: theme.palette.background.paper,
border: '2px solid #000',
boxShadow: theme.shadows[5],
padding: theme.spacing(2, 4, 3),
},
}));
function MainPage() {
const classes = useStyles();
const [modalStyle] = useState(getModalStyle);
const [posts, setPosts] = useState([]);
const [open, setOpen] = useState(false);
const [openSignIn, setOpenSignIn] = useState(false);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [email, setEmail] = useState('');
const [user, setUser] = useState(null);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((authUser) => {
if (authUser) {
console.log(authUser);
setUser(authUser);
} else {
setUser(null);
}
})
return () => {
unsubscribe();
}
}, [user,username]);
useEffect(() => {
db.collection('posts').orderBy('timestamp', 'desc').onSnapshot(snapshot => {
setPosts(snapshot.docs.map(doc => ({
id: doc.id,
post: doc.data()
})));
})
}, []);
const signUp = (event) => {
event.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.then((authUser) => {
authUser.user.updateProfile({
displayName: username
})
})
.catch((error) => alert(error.message));
}
const signIn = (event) => {
event.preventDefault();
auth
.signInWithEmailAndPassword(email, password)
.catch((error) => alert(error.message));
setOpenSignIn(false);
}
return (
<div className="app">
<Modal
open={open}
onClose={() => setOpen(false)}
>
<div style={modalStyle} className={classes.paper}>
<form className="app__signup">
<center>
<img
className="app__headerImage"
src={conspireLogo}
alt="Conspire Logo"
/>
</center>
<Input
placeholder="username"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<Input
placeholder="email"
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<Input
placeholder="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Button type="submit" onClick={signUp}>Sign Up</Button>
</form>
</div>
</Modal>
<Modal
open={openSignIn}
onClose={() => setOpenSignIn(false)}
>
<div style={modalStyle} className={classes.paper}>
<form className="app__signup">
<center>
<img
className="app__headerImage"
src={conspireLogo}
alt="Conspire Logo"
/>
</center>
<Input
placeholder="email"
type="text"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<Input
placeholder="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Button type="submit" onClick={signIn}>Sign In</Button>
</form>
</div>
</Modal>
<div className="app__header">
<img
className="app__headerImage"
src={conspireLogo}
alt="Conspire Logo"
/>
{user ? (
<Button onClick={() => auth.signOut()}>Logout</Button>
): (
<div className="app__loginContainer">
<Button onClick={() => setOpenSignIn(true)}>Sign In</Button>
<Button onClick={() => setOpen(true)}>Sign Up</Button>
</div>
)}
</div>
<div className="app__footer">
<Button onClick={() => setOpenSignIn(true)}><img
className="app__footerImage"
src="http://www.simpleimageresizer.com/_uploads/photos/bdfbb0d1/346a1f4363e1b59f6860fdce6abc1082_2_15.jpg"
alt="Create"
/>
</Button>
</div>
<div className="app__posts">
<div className="app__postsLeft">
{
posts.map(({id, post}) => (
<Post key={id} postId={id} user={user} username={post.username} caption={post.caption} imageUrl={post.imageUrl}></Post>
))
}
</div>
</div>
{user?.displayName ? (
<ImageUpload username={user.displayName} />
): (
<h3 className="center">Sorry you need to login to upload</h3>
)}
</div>
);
}
export default MainPage;
const [modalStyle] = useState(getModalStyle);
You're storing the function reference, not the function's return. Change it to
const [modalStyle] = useState(getModalStyle());
Moreover as you don't need to change this modalStyle, you don't need to have it in state
<div style={getModalStyle()} className={classes.paper}>
I don't think so there should be any error in this file, please check the other files
ex - Post, ImageUpload

Resources