'TypeError: props.onLoggedIn is not a function
I have a main view where users login/register to see movies and the login view page has a function that when you submit, is supposed to query the function in main view.
Main View:
export class MainView extends React.Component {
constructor(props) {
super(props);
// Initial state is set to null
this.state = {
movies: [],
user: null
};
}
componentDidMount() {
let accessToken = localStorage.getItem("token");
if (accessToken !== null) {
this.setState({
user: localStorage.getItem("user"),
});
this.getMovies(accessToken);
}
}
/* When a user successfully logs in, this function updates the `user` property in state to that *particular user*/
onLoggedIn(authData) {
console.log(authData);
this.setState({
user: authData.user.Username,
});
localStorage.setItem("token", authData.token);
localStorage.setItem("user", authData.user.Username);
this.getMovies(authData.token);
}
onLoggedOut() {
localStorage.removeItem("token");
localStorage.removeItem("user");
this.setState({
user: null,
});
}
getMovies(token) {
axios
.get(`https://app.herokuapp.com/movies`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => {
// Assign the result to the state
this.setState({
movies: response.data,
});
})
.catch(function (error) {
console.log(error);
});
}
Login View:
export function LoginView(props) {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
// Declare hook for each input
const [usernameErr, setUsernameErr] = useState("");
const [passwordErr, setPasswordErr] = useState("");
// validate user inputs
const validate = () => {
let isReq = true;
if (!username) {
setUsernameErr("Username required");
isReq = false;
} else if (username.length < 2) {
setUsernameErr("Username must be at least 2 characters long");
isReq = false;
}
if (!password) {
setPasswordErr("Password required");
isReq = false;
} else if (password.length < 6) {
setPassword("Password must be at least 6 characters long");
isReq = false;
}
return isReq;
};
const handleSubmit = (e) => {
e.preventDefault();
const isReq = validate();
if (isReq) {
/* Send request to the server for authentication */
axios
.post(`https://app.herokuapp.com/login`, {
Username: username,
Password: password,
})
.then((response) => {
const data = response.data;
props.onLoggedIn(data);
})
.catch((error) => {
console.log(error, "no such user");
});
}
};
For some reason it tells me that props.onLoggedIn is not a function, which I have already imported in to MainView (I mean LoginView) which should recognise the function. Is there anything that I am missing?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
