So something is wrong with my code but I don't get it where is the wrong..so basically I want to find my items that I registered in my account.. Basically like this code.
const evergreens = [
{ name: "cedar", count: 2 },
{ name: "fir", count: 6 },
{ name: "pine", count: 3 }
];
// suppose we need to skip the first element
const result = evergreens.find((tree, i) => {
if (tree.count > 1 && i !== 0) return true;
});
That is what i saw in this link
And when I tried to get my data in backend it doesn't work.. this is the code..
const [name,setname] = useState()
const [password,setpassword] = useState()
const [key,setkey] = useState()
const [option,setoption] = useState("Register")
const [list,setlist] = useState([])
useEffect(() => {
axios.get('http://localhost:7171/users/')
.then(list => setlist(list.data))
.catch(err => console.log(err))
// console.log(list)
},[])
const handleSubmit = e => {
e.preventDefault()
const Inputs = {key:key, name:name, password:password}
if (option == "Register") {
console.log(list)
// this shows the list of the data []
const findItem = list.find((data,i) =>
data.name === name
)
//but this one doesn't work I don't understand how I just did the same thing though..
console.log(findItem)
//This one will gives an undefined value
// Register(Inputs)
setname("")
setpassword("")
setkey("")
}
}
Does anything I haven't applied here or is there just an error with my codes? I believe I didn't skip anything at here.. I don't understand this thing how it shows an undefined value.
EDITED
(2) [{…}, {…}] 0: {_id: '6232ac00ae5cf39abb58febd', name: 'Hahahatdog', password: '123123123', key: 'ABCDEFGHIJKLMNOP', createdAt: '2022-03-17T03:33:20.809Z', …} 1: {_id: '6232ac14ae5cf39abb58fec0', name: 'cutekabatdog', password: '123123123', key: 'nakoiyakKLMNOP', createdAt: '2022-03-17T03:33:40.339Z', …} length: 2 [[Prototype]]: Array(0)
CodePudding user response:
Based on the code shared here, it seems that the issue comes from the input fields not updating the state properly. Your code for that is:
<input
type="text"
className="form-group-input"
name="name"
onChange={(e) => setname(e)}
/>
And that results in assigning the event (e
) itself in the state, rather than the value, which is in e.target.value
. So doing this should resolve your issue. Additionally, I would advise adding value={name}
as a prop to the input to make the input controlled, thus clearing it when you submit the form. This would result in:
<input
type="text"
className="form-group-input"
name="name"
onChange={(e) => setname(e.target.value)}
value={name}
/>
You can read more on controlled components in React here.