- #1
Pyrexx
- 5
- 0
- TL;DR Summary
- I am trying to call a function from another JS File, but the error "Error logging in: onLoginSuccess is not a function" keeps popping up
This is the component for Authors to Login to the Web Application
This is the parent component used to help handle authors updating their details and authentication for authors to get access to respective parts of the pages
This is where the function is defined and where I want to call the function from but with no success, despite me trying everything
```
```
JavaScript:
import { Button, CircularProgress, Fade, Link, TextField, Typography } from '@material-ui/core';
import { ThemeProvider, createTheme, makeStyles } from '@material-ui/core/styles';
import axios from 'axios';
import React, { useState } from 'react';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import backgroundImage from './background.jpg';
import ParentComponent from './ParentComponent';
const theme = createTheme({
palette: {
primary: {
main: '#00bcd4', // Cyan color
},
error: {
main: '#ff1744', // Error color
},
},
});
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minHeight: '100vh',
backgroundImage: `url(${backgroundImage})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
},
formContainer: {
maxWidth: 400,
width: '100%',
padding: theme.spacing(4),
borderRadius: theme.shape.borderRadius,
boxShadow: theme.shadows[5],
backgroundColor: '#fff',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
form: {
width: '100%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
textField: {
width: '100%',
marginBottom: theme.spacing(3),
},
button: {
marginTop: theme.spacing(2),
width: '100%',
maxWidth: 200,
padding: theme.spacing(1.5),
},
title: {
fontFamily: 'Roboto, sans-serif',
fontWeight: 700,
fontSize: '2.5rem',
color: theme.palette.primary.main,
marginBottom: theme.spacing(3),
textAlign: 'center',
textShadow: '2px 2px 4px rgba(0, 0, 0, 0.3)',
},
error: {
marginTop: theme.spacing(2),
color: theme.palette.error.main,
textAlign: 'center',
},
link: {
marginTop: theme.spacing(2),
textAlign: 'center',
},
}));
const AuthorLogin = ({ onLoginSuccess, onLoginError }) => { // Accept onLoginSuccess as a prop
const classes = useStyles();
const navigate = useNavigate();
const [formData, setFormData] = useState({
email: '',
password: '',
});
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
try {
const response = await axios.post('http://localhost:5000/api/author/login', formData);
console.log('Login successful:', response.data);
// Redirect to writing portfolio upon successful login
navigate('/writingPortfolio');
console.log("Calling onLoginSuccess...");
// Log the type of onLoginSuccess
onLoginSuccess(); // Attempt to call onLoginSuccess // Call onLoginSuccess upon successful login
} catch (error) {
onLoginError(error.message);
console.error('Error logging in:', error.response ? error.response.data.message : error.message);
setError(error.response ? error.response.data.message : error.message);
}
setLoading(false);
};
return (
<div className={classes.root}>
<Fade in={true} timeout={1500}>
<div className={classes.formContainer}>
<ThemeProvider theme={theme}>
<Typography variant="h1" className={classes.title}>
Author Login
</Typography>
<form onSubmit={handleSubmit} className={classes.form}>
<TextField
type="email"
label="Email"
name="email"
value={formData.email}
onChange={handleChange}
variant="outlined"
className={classes.textField}
required
placeholder="Enter your email"
/>
<TextField
type="password"
label="Password"
name="password"
value={formData.password}
onChange={handleChange}
variant="outlined"
className={classes.textField}
required
placeholder="Enter your password"
/>
<Button
type="submit"
variant="contained"
color="primary"
className={classes.button}
disabled={loading}
>
{loading ? <CircularProgress size={24} color="inherit" /> : 'Login'}
</Button>
{error && <Typography variant="body2" className={classes.error}>{error}</Typography>}
</form>
<Typography variant="body2" className={classes.link}>
Don't have an account?{' '}
<Link component={RouterLink} to="/AuthorRegistration">
Sign up
</Link>
</Typography>
</ThemeProvider>
</div>
</Fade>
</div>
);
};
export default AuthorLogin;
This is the parent component used to help handle authors updating their details and authentication for authors to get access to respective parts of the pages
This is where the function is defined and where I want to call the function from but with no success, despite me trying everything
```
Parent Component:
// ParentComponent.js
import React, { useState } from 'react';
import AuthorDashboard from './AuthorDashboard';
import AuthorLogin from './AuthorLogin';
import AuthorProfile from './AuthorProfile';
import AuthorSettings from './AuthorSettings';
const ParentComponent = () => {
const [author, setAuthor] = useState(null);
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [error, setError] = useState(null);
const handleUpdateAuthor = (updatedAuthor) => {
setAuthor(updatedAuthor);
};
const handleLoginSuccess = async () => {
setIsAuthenticated(true);
try {
const response = await fetch('/author');
const author = await response.json();
setAuthor(author);
setError(null);
console.log("handleLoginSuccess is a function:", typeof handleLoginSuccess === "function");
// Clear any previous errors on successful login
} catch (error) {
console.error('Error handling login success:', error);
setError('An error occurred while handling login success.');
}
};
function handleLoginError (errorMessage) {
setError(errorMessage);
};
return (
<div>
{isAuthenticated ? (
<>
<AuthorSettings author={author} onUpdateAuthor={handleUpdateAuthor} />
<AuthorProfile author={author} />
<AuthorDashboard isAuthenticated={isAuthenticated} authorId={author.id} />
</>
) : (
<AuthorLogin onLoginSuccess={handleLoginSuccess} onLoginError={handleLoginError} />
)}
{error && <p style={{ color: 'red' }}>{error}</p>}
</div>
);
};
export default ParentComponent;