Reputation: 75
When i press the submit button i am getting this error, TypeError: setUser is not a function. I am trying to get the data from a form and store it.
APP.JS
import React, { useState } from 'react';
import User from './Components/User';
import Card from './Components/Card';
function App() {
const {user, setUser} = useState([{username: "", age: 1}]);
const handleUserAdd = (user1) => {
setUser(user1);
console.log(user);
}
return (
<div className="App">
<Card>
<User onUserAdd={handleUserAdd}/>
</Card>
</div>
);
}
export default App;
USER.JS
import React, { useState } from 'react';
const User = (props) => {
const {name, setName} = useState("");
const {years, setYears} = useState(1);
const handleOnNameChange = (e) => {
setName(e.target.value);
}
const handleOnAgeChange = (e) => {
setYears(e.target.value);
}
const handleOnSubmit = (e) =>{
e.preventDefault();
const user = {
username: name,
age: years
};
props.onUserAdd(user);
setName("");
setYears();
}
return (
<>
<form onSubmit={handleOnSubmit}>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">Username:</label>
<input class="form-control" aria-describedby="emailHelp" value={name} onChange={handleOnNameChange} />
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label">Age:</label>
<input type="number" min={1} max={120} class="form-control" value={years} onChange={handleOnAgeChange} />
</div>
<button type="submit" class="btn btn-primary">Add User</button>
</form>
</>
);
}
export default User;
Screenshot of the error
This also happens when i type into the input boxes:
I've used the useState hook before and it never happened, i'd be grateful if you could help me solve this!
Upvotes: 2
Views: 9006
Reputation: 1
This is incorrect
const { user, setUser } = useState("");
This is correct
const [user, setUser] = useState("");
Upvotes: 0
Reputation: 2090
useState
returns an array not an object. You should destructure it like this;
const [user, setUser] = useState([{username: "", age: 1}]);
Upvotes: 11