having error with the .map function in the code of mine - javascript

read.js:73 Uncaught TypeError: APIData.map is not a function. I am facing this error when I changed the existing API which was a need to do and even there is one more problem I am facing other than this error is that in my registration form my the entered data is taking data but it is not stored in the database so there is a problem.
at Read (read.js:73:1)
at renderWithHooks (react-dom.development.js:16305:1)
at updateFunctionComponent (react-dom.development.js:19588:1)
at beginWork (react-dom.development.js:21601:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
create.js(registration form code)
import React, { useState } from 'react';
import { Button, Form } from 'semantic-ui-react'
import axios from 'axios';
import { useNavigate } from 'react-router';
export default function Create() {
let navigate = useNavigate();
const [Employee_name, setEmployee_name] = useState('');
const [Employee_id, setEmployee_id] = useState('');
const [Employee_address, setEmployee_address] = useState('');
const [Employee_post, setEmployee_post] = useState('');
const [username, setusername] = useState('');
const [Employee_password, setEmployee_password] = useState('');
const postData = (e) => {
e.preventDefault();
if (Employee_name, Employee_id, Employee_address, Employee_post, username, Employee_password.length === 0) {
alert('Enter Employee Details to register!')
return false
}
if (Employee_name.length === 0) {
alert('Enter Employee Name!')
return false
}
if (Employee_id.length === 0) {
alert('Enter Employee id!')
return false
}
if (Employee_address.length === 0) {
alert('Enter Employee address!')
return false
}
if (Employee_post.length === 0) {
alert('Enter Employee Position!')
return false
}
if (username.length === 0) {
alert('Set Employee Username!')
return false
}
if (Employee_password.length === 0) {
alert('Set Employee Password!')
return false
}
axios.post(`http://localhost:4000/api/users/`, {
Employee_name,
Employee_id,
Employee_address,
Employee_post,
username,
Employee_password
})
.then(() => {
navigate('/Login')
})
alert('Data Saved')
}
return (
<div>
<Form className="create-form" onSubmit={e => postData(e)}>
<h2 className='Header'>Employee Registration form</h2>
<Form.Field required={true}>
<label>Employee Name</label>
<input type='text' placeholder='Employee Name' onChange={(e) => setEmployee_name(e.target.value)} />
</Form.Field>
<Form.Field required={true}>
<label>Employee ID</label>
<input type='text' placeholder='Employee ID' onChange={(e) => setEmployee_id(e.target.value)} />
</Form.Field>
<Form.Field required={true}>
<label>Employee Address</label>
<input type='text' placeholder='Employee Address' onChange={(e) => setEmployee_address(e.target.value)} />
</Form.Field>
<Form.Field required={true}>
<label>Employee Position</label>
<input type='text' placeholder='Employee Position' onChange={(e) => setEmployee_post(e.target.value)} />
</Form.Field>
<Form.Field required={true}>
<label>Create Username</label>
<input type='text' placeholder='Username' onChange={(e) => setusername(e.target.value)} />
</Form.Field>
<Form.Field required={true}>
<label>Create Password</label>
<input type='password' placeholder='Password' onChange={(e) => setEmployee_password(e.target.value)} />
</Form.Field>
<Button className='b2' onClick={postData} type='submit'>Submit</Button>
</Form>
</div>
)
}
read.js(the error 'read.js:73 Uncaught TypeError: APIData.map is not a function')
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { Table, Button } from 'semantic-ui-react';
import { useNavigate } from 'react-router-dom';
export default function Read() {
let navigate = useNavigate();
const [APIData, setAPIData] = useState([]);
useEffect(() => {
axios.get(`http://localhost:4000/api/users/`)
.then((response) => {
console.log(response.data)
setAPIData(response.data);
})
}, []);
const setData = (data) => {
let { Employee_name, Employee_id, Employee_address, Employee_post, username, Employee_password } = data;
localStorage.setItem('Employee ID', Employee_id);
navigate('/update')
}
const getData = () => {
axios.get(`http://localhost:4000/api/users/`)
.then((getData) => {
setAPIData(getData.data);
})
}
const onDelete = (data) => {
const { Employee_id } = data
if (Employee_id === 0) {
alert("Employee id not found")
return
}
const url = `http://localhost:4000/api/users/${Employee_id}`
axios.delete(url)
.then((res) => {
getData();
})
.catch(err => console.log(err))
alert('Employee Deleted!')
}
const Data = () => {
navigate('/login')
}
return (
<form>
<h2>Registered Employees</h2>
<div>
<Table singleLine>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Employee Name</Table.HeaderCell>
<Table.HeaderCell>Employee ID</Table.HeaderCell>
<Table.HeaderCell>Employee Address</Table.HeaderCell>
<Table.HeaderCell>Employee Position</Table.HeaderCell>
<Table.HeaderCell>Employee Username</Table.HeaderCell>
<Table.HeaderCell>Employee Password</Table.HeaderCell>
<Table.HeaderCell>Update</Table.HeaderCell>
<Table.HeaderCell>Delete</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{APIData.map((data, index) => {
return (
<Table.Row key={index + ""}>
<Table.Cell>{data.Employee_name}</Table.Cell>
<Table.Cell>{data.Employee_id}</Table.Cell>
<Table.Cell>{data.Employee_address}</Table.Cell>
<Table.Cell>{data.Employee_post}</Table.Cell>
<Table.Cell>{data.username}</Table.Cell>
<Table.Cell>{data.Employee_password}</Table.Cell>
{/* <Link to='/update'> */}
<Table.Cell>
<Button onClick={() => setData(data)}>Update</Button>
</Table.Cell>
{/* </Link> */}
<Table.Cell>
<Button onClick={() => onDelete(data)}>Delete</Button>
</Table.Cell>
</Table.Row>
)
})}
</Table.Body>
</Table>
<Button onClick={Data} type='submit'>Home</Button>
</div>
</form>
)
}

Related

TypeError: Converting circular structure to JSON when sending a post request through axios

Im getting this error when I send a post request to the server when the role for the user is seller for which there are 2 extra properties for the JSON : resName and resAddress. I am also using placeautocomplete (from google) to get the address of the restaurant (the name of it can be anything for the time being).
Register.js:
import logo from './logo.svg';
import './App.css';
import React, { Component, useEffect } from 'react';
import { useState } from 'react';
import axios from 'axios';
import LocationSearchInput from './placeComplete';
function Register() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [role, setRole] = useState("seller");
const [resName, setResName] = useState("");
const [resAddress, setResAddress] = useState(React.createRef());
async function registerUser(e){
e.preventDefault();
if (role === 'seller'){
const restaurantAddress = resAddress.current
console.log(restaurantAddress.state.address, resName)
}
const response = await axios.post('/api/users/register',
{
name,
email,
password,
resName,
resAddress,
role
}
).then(
res => {
console.log(res.data)
}
)
}
function registerRestaurant(){
if (role === 'seller'){
return(
<div>
<h4>Restaurant Name:</h4> <br />
<input type='text'
placeholder='Restaurant Name'
value={resName}
onChange={(e) => setResName(e.target.value)}
/>
<br />
<LocationSearchInput ref={resAddress} />
</div>
);
}
}
return (
<div>
<form onSubmit={registerUser}>
<input type="name" placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<br />
<input type="email" placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<br />
<input type="password" placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<br />
<input type='radio' value='customer'
checked={role === 'customer'}
onChange={(e) => {
setRole(e.target.value)
}}
/>
customer
<br />
<input type='radio' value='seller'
checked={role === 'seller'}
onChange={(e) => {
setRole(e.target.value)
}}
/>
seller
<br />
{registerRestaurant()}
<input type='submit' value='Register' />
</form>
</div>
);
}
export default Register;
placeComplete.js:
import React from 'react';
import PlacesAutocomplete, {
geocodeByAddress,
getLatLng,
} from 'react-places-autocomplete';
class LocationSearchInput extends React.Component {
constructor(props) {
super(props);
this.state = { address: '' };
}
handleChange = address => {
this.setState({ address });
};
handleSelect = address => {
geocodeByAddress(address)
.then(results => getLatLng(results[0]))
.then(latLng => console.log('Success', latLng))
.then(this.setState({address: address}))
.catch(error => console.error('Error', error));
};
render() {
return (
<PlacesAutocomplete
value={this.state.address}
onChange={this.handleChange}
onSelect={this.handleSelect}
>
{({ getInputProps, suggestions, getSuggestionItemProps, loading }) => (
<div>
<input
{...getInputProps({
placeholder: 'Search Places ...',
className: 'location-search-input',
})}
/>
<div className="autocomplete-dropdown-container">
{loading && <div>Loading...</div>}
{suggestions.map(suggestion => {
const className = suggestion.active
? 'suggestion-item--active'
: 'suggestion-item';
// inline style for demonstration purpose
const style = suggestion.active
? { backgroundColor: '#fafafa', cursor: 'pointer' }
: { backgroundColor: '#ffffff', cursor: 'pointer' };
return (
<div
{...getSuggestionItemProps(suggestion, {
className,
style,
})}
>
<span>{suggestion.description}</span>
</div>
);
})}
</div>
</div>
)}
</PlacesAutocomplete>
);
}
}
export default LocationSearchInput;
I am also getting the following warning when I start typing in resAddress:
react_devtools_backend.js:4026 Warning: Each child in a list should have a unique "key" prop. Check the render method of `PlacesAutocomplete`. See https://reactjs.org/link/warning-keys for more information.
Mind you the server is accepting requests through postman.
This error usually gets thrown if you're not sending proper JSON. Your problem seems to happen here:
const response = await axios.post('/api/users/register',
{
name,
email,
password,
resName,
resAddress,
role
}
).then(
res => {
console.log(res.data)
}
)
Since resAddress is a ref (not proper JSON):
const [resAddress, setResAddress] = useState(React.createRef());
Change to something like this and you should be fine:
{
/* ... */
resAddress: resAddress.current.state.address
/* ... */
}

Error: Cannot read property "name" of undefined. However, after the page is refreshed, the error is removed

I have the following code for when the profile route is being called:
import React, { useState, useEffect } from 'react'
import { Row, Col, Form, Button } from 'react-bootstrap'
import { useDispatch, useSelector } from 'react-redux'
import Message from '../components/Message'
import Loader from '../components/Loader'
import { getUserDetails } from '../actions/userActions'
const ProfileScreen = ({ location, history }) => {
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const dispatch = useDispatch()
const userDetails = useSelector((state) => state.userDetails)
const { loading, user, error } = userDetails
const userLogin = useSelector((state) => state.userLogin)
const { userInfo } = userLogin
useEffect(() => {
if (!userInfo) {
history.push('/login')
} else {
if (!user.name) {
dispatch(getUserDetails('profile'))
} else {
setName(user.name)
setEmail(user.email)
}
}
}, [history, userInfo, dispatch, user])
const submitHandler = (e) => {
e.preventDefault()
// DISPATCH PROFILE UPDATE
}
return (
<Row>
<Col md={3}>
<h1>Sign Up</h1>
{error && <Message variant='danger'>{error}</Message>}
{loading && <Loader />}
<Form onSubmit={submitHandler}>
<Form.Group controlId='name'>
<Form.Label>Full Name</Form.Label>
<Form.Control
type='name'
placeholder='Enter your Full Name'
value={name}
onChange={(e) => setName(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId='email'>
<Form.Label>Email Address</Form.Label>
<Form.Control
type='email'
placeholder='Enter your email address'
value={email}
onChange={(e) => setEmail(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId='password' className='my-3'>
<Form.Label>Password</Form.Label>
<Form.Control
type='password'
placeholder='Enter your password'
value={password}
onChange={(e) => setPassword(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId='confirmPassword' className='my-3'>
<Form.Label>Confirm Password</Form.Label>
<Form.Control
type='password'
placeholder='Confirm your password'
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
></Form.Control>
</Form.Group>
<Button type='submit' variant='primary' className='my-4'>
Update
</Button>
</Form>
</Col>
<Col md={9}>
<h2>My Orders</h2>
</Col>
</Row>
)
}
export default ProfileScreen
After the code is being executed, and the user goes to the profile route, at first it shows "Cannot read property 'name' of undefined"
however after the page is being refreshed, the error gets removed and the app then works completely fine.
This is the error being shown
Please check your condition.
useEffect(() => {
if (!userInfo) {
history.push('/login')
} else {
if (Object.keys(user).length === 0) {
dispatch(getUserDetails('profile'))
} else {
setName(user.name)
setEmail(user.email)
}
}
}, [history, userInfo, dispatch, user])

React error: warning maximum update depth exceeded

I have added a screen from where admin can add products to store. Whenever I try to enter this page I get following warning and it keeps on repeating until my browser freezes or crashes:
Maximum update depth exceeded. This can happen when a component calls
setState inside useEffect, but useEffect either doesn't have a
dependency array, or one of the dependencies changes on every render.
Here is the code for my ProductEditScreen.js
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import ErrorMessage from "../../components/ErrorMessage/ErrorMessage";
import Loader from "../../components/Loader/Loader";
import { Link } from "react-router-dom";
import { listProductDetails } from "../../redux/actions/productActions";
import "./ProductEditScreen.scss";
const ProductEditScreen = ({ match, history }) => {
const productID = match.params.id;
const [name, setName] = useState("");
const [price, setPrice] = useState(0);
const [image, setImage] = useState("");
const [brand, setBrand] = useState("");
const [category, setCategory] = useState("");
const [countInStock, setCountInStock] = useState(0);
const [description, setDescription] = useState("");
const dispatch = useDispatch();
const productDetails = useSelector((state) => state.productDetails);
const { loading, error, product } = productDetails;
useEffect(() => {
if (!product.name || product._id !== productID) {
dispatch(listProductDetails(productID));
} else {
setName(product.name);
setPrice(product.price);
setImage(product.Image);
setBrand(product.brand);
setCategory(product.category);
setCountInStock(product.setCountInStock);
setDescription(product.description);
}
}, [dispatch, history, product, productID]);
const submitHandler = (e) => {
e.preventDefault();
};
return (
<>
<div className="userEdit-container">
{/* {loadingUpdate && <Loader />}
{errorUpdate && <ErrorMessage>{errorUpdate}</ErrorMessage>} */}
<div className="userEdit-form">
<h1>EDIT PRODUCT</h1>
{error ? (
<ErrorMessage>{error}</ErrorMessage>
) : (
<form onSubmit={submitHandler}>
<div className="userEdit-form-items">
<input
className="userEdit-input"
type="name"
placeholder="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
className="userEdit-input"
type="number"
placeholder="Price"
value={price}
onChange={(e) => setPrice(e.target.value)}
/>
<input
className="userEdit-input"
type="text"
placeholder="Enter image url"
value={image}
onChange={(e) => setImage(e.target.value)}
/>
<input
className="userEdit-input"
type="text"
placeholder="Brand Name"
value={brand}
onChange={(e) => setBrand(e.target.value)}
/>
<input
className="userEdit-input"
type="text"
placeholder="Category"
value={category}
onChange={(e) => setCategory(e.target.value)}
/>
<input
className="userEdit-input"
type="number"
placeholder="Count In Stock"
value={countInStock}
onChange={(e) => setCountInStock(e.target.value)}
/>
<input
className="userEdit-input"
type="text"
placeholder="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<button type="submit" value="submit">
UPDATE
</button>
<Link to="/admin/productlist">
<button>Go Back</button>
</Link>
</div>
</form>
)}
</div>
</div>
</>
);
};
export default ProductEditScreen;
warning says useEffect either doesn't have a dependency array but I have passed all the dependencies. Also, I don't see any dependency changing every render.
As Chris G suggested above in comments I first ran useEffect with empty [] and then added what console recommended me.
useEffect(() => {
if (!product.name || product._id !== productID) {
dispatch(listProductDetails(productID));
} else {
setName(product.name);
setPrice(product.price);
setImage(product.Image);
setBrand(product.brand);
setCategory(product.category);
setCountInStock(product.setCountInStock);
setDescription(product.description);
}
}, [
dispatch,
productID,
product.Image,
product._id,
product.brand,
product.name,
product.price,
product.category,
product.setCountInStock,
product.description,
]);

React js image uploder code with firebase cloud storage gives error?

I am creating a instagram clone and I have made it with react js and database is cloud firestore, and using Cloud Storage for storing images.
I am getting error in ImageUpload.js when I am clicking on upload button and progress bar does not show any progress in console.
The folowing error is shown:
FirebaseStorageError {code_: "storage/invalid-argument", message_: "Firebase Storage: Invalid argument in on at inde…Expected one of the event types: [state_changed].", serverResponse_: null, name_: "FirebaseError"}
code of ImageUpload.js
import React, { useState, useEffect } from "react";
import "./App.css";
import Post from "./Post";
import { db, auth } from "./firebase";
import Modal from "#material-ui/core/Modal";
import { makeStyles } from "#material-ui/core/styles";
import { Button, Input } from "#material-ui/core";
import ImageUpload from "./ImageUpload";
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, setsPosts] = 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 ::--> Runs a piece of code based on a specific condition
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((authUser) => {
if (authUser) {
//user has logged in....
console.log(authUser);
setUser(authUser);
} else {
//user has logged out....
setUser(null);
}
});
return () => {
//perform some cleanup actions
unsubscribe();
};
}, [user, username]);
useEffect(() => {
//this is where the code runs
db.collection("posts").onSnapshot((snapshot) => {
//every time a new post is added,this code firebase
setsPosts(
snapshot.docs.map((doc) => ({
id: doc.id,
post: doc.data(),
}))
);
});
}, []);
const signUp = (event) => {
event.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.then((authUser) => {
return authUser.user.updateProfile({
displayName: username,
});
})
.catch((error) => alert(error.message));
setOpen(false);
};
const signIn = (event) => {
event.preventDefault();
auth
.signInWithEmailAndPassword(email, password)
.catch((error) => alert(error.message));
setOpenSignIn(false);
};
return (
<div className="app">
{user?.displayName ? (
<ImageUpload username={user.displayName} />
) : (
<h3>Sorry you need to login to upload</h3>
)}
<Modal open={open} onClose={() => setOpen(false)}>
<div style={modalStyle} className={classes.paper}>
<form className="app__signup">
<center>
<img
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo-2x.png/1b47f9d0e595.png"
alt=""
/>
</center>
<Input
placeholder="usermane"
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
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo-2x.png/1b47f9d0e595.png"
alt=""
/>
</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 Up
</Button>
</form>
</div>
</Modal>
<div className="app__header">
<img
className="app__headerImage"
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo-2x.png/1b47f9d0e595.png"
alt=""
/>
</div>
{user ? (
<Button onClick={() => auth.signOut()}>Log Out</Button>
) : (
<div className="app__loginContainer">
<Button onClick={() => setOpenSignIn(true)}>Sign In</Button>
<Button onClick={() => setOpen(true)}>Sign Up</Button>
</div>
)}
{/* <h1>Lets built ig-clone with React</h1> */}
{posts.map(({ id, post }) => (
<Post
key={id}
username={post.username}
caption={post.caption}
imageUrl={post.imageUrl}
/>
))}
{/* <Post
username="cleverqazi"
caption="WoW is works"
imageUrl="https://pbs.twimg.com/profile_images/446356636710363136/OYIaJ1KK_400x400.png"
/>
<Post
username="ssssangha"
caption="Dope"
imageUrl="https://images.unsplash.com/photo-1599687266197-6c66c083b39c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1534&q=80https://images.unsplash.com/photo-1599687266197-6c66c083b39c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9"
/>
<Post
username="amatsf"
caption="This is fun Project"
imageUrl="https://images.unsplash.com/photo-1600872844932-f95ce063b94c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9"
/>
Post */}
</div>
);
}
export default App;
code from App.js
import React, { useState, useEffect } from "react";
import "./App.css";
import Post from "./Post";
import { db, auth } from "./firebase";
import Modal from "#material-ui/core/Modal";
import { makeStyles } from "#material-ui/core/styles";
import { Button, Input } from "#material-ui/core";
import ImageUpload from "./ImageUpload";
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, setsPosts] = 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 ::--> Runs a piece of code based on a specific condition
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((authUser) => {
if (authUser) {
//user has logged in....
console.log(authUser);
setUser(authUser);
} else {
//user has logged out....
setUser(null);
}
});
return () => {
//perform some cleanup actions
unsubscribe();
};
}, [user, username]);
useEffect(() => {
//this is where the code runs
db.collection("posts").onSnapshot((snapshot) => {
//every time a new post is added,this code firebase
setsPosts(
snapshot.docs.map((doc) => ({
id: doc.id,
post: doc.data(),
}))
);
});
}, []);
const signUp = (event) => {
event.preventDefault();
auth
.createUserWithEmailAndPassword(email, password)
.then((authUser) => {
return authUser.user.updateProfile({
displayName: username,
});
})
.catch((error) => alert(error.message));
setOpen(false);
};
const signIn = (event) => {
event.preventDefault();
auth
.signInWithEmailAndPassword(email, password)
.catch((error) => alert(error.message));
setOpenSignIn(false);
};
return (
<div className="app">
{user?.displayName ? (
<ImageUpload username={user.displayName} />
) : (
<h3>Sorry you need to login to upload</h3>
)}
<Modal open={open} onClose={() => setOpen(false)}>
<div style={modalStyle} className={classes.paper}>
<form className="app__signup">
<center>
<img
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo-2x.png/1b47f9d0e595.png"
alt=""
/>
</center>
<Input
placeholder="usermane"
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
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo-2x.png/1b47f9d0e595.png"
alt=""
/>
</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 Up
</Button>
</form>
</div>
</Modal>
<div className="app__header">
<img
className="app__headerImage"
src="https://www.instagram.com/static/images/web/mobile_nav_type_logo-2x.png/1b47f9d0e595.png"
alt=""
/>
</div>
{user ? (
<Button onClick={() => auth.signOut()}>Log Out</Button>
) : (
<div className="app__loginContainer">
<Button onClick={() => setOpenSignIn(true)}>Sign In</Button>
<Button onClick={() => setOpen(true)}>Sign Up</Button>
</div>
)}
{/* <h1>Lets built ig-clone with React</h1> */}
{posts.map(({ id, post }) => (
<Post
key={id}
username={post.username}
caption={post.caption}
imageUrl={post.imageUrl}
/>
))}
{/* <Post
username="cleverqazi"
caption="WoW is works"
imageUrl="https://pbs.twimg.com/profile_images/446356636710363136/OYIaJ1KK_400x400.png"
/>
<Post
username="ssssangha"
caption="Dope"
imageUrl="https://images.unsplash.com/photo-1599687266197-6c66c083b39c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1534&q=80https://images.unsplash.com/photo-1599687266197-6c66c083b39c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9"
/>
<Post
username="amatsf"
caption="This is fun Project"
imageUrl="https://images.unsplash.com/photo-1600872844932-f95ce063b94c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9"
/>
Post */}
</div>
);
}
export default App;
code of firebase.js
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
import firebase from "firebase";
const firebaseapp = firebase.initializeApp({
apiKey: "AIzaSyAOozRFYMCWRQYQ4DZg19LB-8naEiL7WDvWE",
authDomain: "instagram-clone-react-cc16f.firebaseapp.com",
databaseURL: "https://instagram-react-cc16f.firebaseio.com",
projectId: "instagram-clone-react-cc6f",
storageBucket: "instagram-clone-react-cc16f.appspot.com",
messagingSenderId: "602134433443",
appId: "1:602189635954:web:d2d9096d64345349101bdeb",
measurementId: "G-CW4M24VATZ",
});
const db = firebaseapp.firestore();
const auth = firebase.auth();
const storage = firebase.storage();
export { db, auth, storage };
You must add handleUpload to the button you send the picture.
function ImageUpload({ username }) {
const [caption, setCaption] = useState("");
const [image, setImage] = useState(null);
const [progress, setProgress] = useState(0);
const handleChange = (e) => {
if (e.target.files[0]) {
setImage(e.target.files[0]);
}
};
const handleUpload = () => {
const uploadTask = storage.ref(`images/${image.name}`).put(image);
uploadTask.on(
"state_changed",
(snapshot) => {
//progress function
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(progress);
},
(error) => {
//error function
console.log(error);
alert(error.message);
},
() => {
//complete function
storage
.ref("images")
.child(image.name)
.getDownloadURL()
.then((url) => {
//post image inside db
db.collection("posts").add({
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
caption: caption,
imageUrl: url,
username: username,
});
setProgress(0);
setCaption("");
setImage(null);
});
}
);
};
return (
<div>
{/*
- I want to have ...
- Caption input
- File picture*/}
<progress value={progress} max="100" />
<input
type="text"
placeholder="Enter a caption..."
onChange={(event) => setCaption(event.target.value)}
value={caption}
/>
<input type="file" onChange={handleChange} />
<Button onClick={handleUpload}>Upload</Button>
</div>
);
}
export default ImageUpload;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Check user name availability from firebase in react

I am currently stuck on checking unique username in the sign up(on firebase) in react. My goal is that
1. when the user input the username, the function checkNameAvalaible go to the firebase database and check if the name exists.
2.if the name exists set the state of usernameavalaible to false, and set it to true if name works
3.disable the submit button of the sign up if the usernameavalaible is false.
4.If the username is taken, use helper text in textfield to alert the current user.
I am stuck with the if statement, I tried a few times and it is not working here is my code
import React, { Component } from "react";
import { Link } from "react-router-dom";
import { auth } from "../firebase";
import { db} from "../firebase";
import "./auth.css";
import * as routes from "../constants/routes";
import { SignInLink } from "./SignIn";
import TextField from "#material-ui/core/TextField";
import Button from "#material-ui/core/Button";
const SignUpPage = ({ history }) => (
<div align="center" className="SignUpBox">
<h1>SignUp</h1>
<SignUpForm history={history} />
<SignInLink />
</div>
);
const INITIAL_STATE = {
username: "",
name: "",
email: "",
passwordOne: "",
passwordTwo: "",
error: null
};
const byPropKey = (propertyName, value) => () => ({
[propertyName]: value
});
class SignUpForm extends Component {
state = { ...INITIAL_STATE };
// checkPassword() {
// if(!this.state.passwordOne || this.state.passwordOne !== this.state.passwordTwo){
// this.setState({error:"passwords do not match"});
// }
// else {
// this.setState({error:null});
// }
// }
onSubmit = event => {
event.preventDefault();
const { email, passwordOne, name, username } = this.state;
auth
.doCreateUserWithEmailAndPassword(
email,
passwordOne,
name,
username
)
.then(authUser => {
this.setState(() => ({ ...INITIAL_STATE }));
this.props.history.push(routes.HOME);
})
.catch(error => {
this.setState(byPropKey("error", error));
});
};
render() {
var usernameAvalaible
const {
username,
name,
email,
passwordOne,
passwordTwo,
error
} = this.state;
checkNameAvalaible(){
if (db.doc(`/users/${username}`).get().exists){
this.setState{usernameAvalaible:false};
}
else{
this.setState{usernameAvalaible:true};
}
};
const isInvalid =
passwordOne !== passwordTwo ||
passwordOne === "" ||
email === "" ||
name === "" ||
username === ""|| usernameAvalaible===false;
return (
<form onSubmit={this.onSubmit}>
<TextField
name="Username"
id="standard-secondary"
label="User name"
color="primary"
value={username}
onChange={event =>
this.setState(byPropKey("username", event.target.value))
}
type="text"
/>
<TextField
name="name"
value={name}
id="standard-secondary"
label="Full name"
color="primary"
onChange={event =>
this.setState(byPropKey("name", event.target.value))
}
type="text"
/>
<TextField
name="email"
value={email}
id="standard-secondary"
label="Email Address"
color="primary"
onChange={event =>
this.setState(byPropKey("email", event.target.value))
}
type="email"
/>
<TextField
name="password"
value={passwordOne}
id="standard-secondary"
label="Password"
color="primary"
onChange={event =>
this.setState(byPropKey("passwordOne", event.target.value))
}
type="password"
/>
<TextField
name="ConfirmPassword"
value={passwordTwo}
id="standard-secondary"
label="Comfirm Password"
color="primary"
onChange={event =>
this.setState(byPropKey("passwordTwo", event.target.value))
}
type="password"
/>
<br />
<br />
<Button
type="submit"
disabled={isInvalid}
variant="contained"
color="primary"
>
Sign Up
</Button>
{error && <p style={{ color: "red" }}>{error.message}</p>}
</form>
);
}
}
const SignUpLink = () => (
<p>
Don't have an account? <Link to={routes.SIGN_UP}>Sign Up</Link>
</p>
);
export default SignUpPage;
export { SignUpForm, SignUpLink };

Categories

Resources