I’m trying to save the values typed in the Input inside the state variable. But when I type any value into the input that calls the HandleInstitution
function I get the following error: Uncaught TypeError: educations is undefined
.
I’m a beginner in React, can someone help me?
My code:
import '../styles/education.css';
import { useState } from 'react';
function Education(){
var [educations, setEducations] = useState(
[
{
id: 1,
institution: '',
course: '',
date: '',
},
]
);
function handleAddEducation(){
setEducations([
...educations,
{
id: educations.length + 1,
institution: '',
course: '',
date: '',
},
]);
}
function HandleInstitution(event, id){
const { name, value } = event.target;
setEducations((prevEducation) => {
prevEducation.map((educationItem) => {
if(educationItem.id === id){
educationItem.institution=value;
}
})
});
}
return (
<div className="background" id="education">
<h2>Education</h2>
{educations.map((education) => (
<div className="form" key={education.id}>
<div className="input" type="text">
<label htmlFor={`inputInstitution-${education.id}`}>Institution name: </label>
<input type="text" onChange={ (event) => { HandleInstitution(event, education.id) } } name={`inputInstitution-${education.id}`} placeholder="Enter the name of your school or university" required></input>
</div>
<div className="input">
<label htmlFor={`inputCourse-${education.id}`}>Course Name: </label>
<input name={`inputCourse-${education.id}`} type="text" placeholder="Enter the name of your course" required></input>
</div>
<div className="input">
<label htmlFor={`dateInput-${education.id}`}>Date of conclusion: </label>
<input name={`dateInput-${education.id}`} type="date" required></input>
</div>
</div>
))}
<button type="submit" onClick={ handleAddEducation }>Add Education</button>
</div>
);
}
export default Education;
2
Answers
You may also be getting an error that says:
Unexpected var, use let or const instead.
You should change the line that makes theeducations
state to be:The
setEducations
function should be called with a new education array or a function that will return a new education array. Perhaps:when you create a function/arrow function
setEducations((prevEducation) => {}
then you should return a value, otherwise, it will gonna returnundefined
. In your case, it will gonna returnundefined
and set it toeductions
state.