Hello, I hope everyone is doing great, I have been dealing with this issue for the past couple of days and I have searched and tried so many ways to implement the following functionality on a small react project I am building.
here is a link to what I’m trying to achieve
below is my code so far.
This is the component where I’m fetching the data that I need from an external API
##DataLoad component
import axios from "axios";
import { InputField } from './Input';
export class StudentList extends React.Component{
constructor(props){
super(props);
this.state = {
students: [],
input: "",
};
this.handleChange = this.handleChange.bind(this)
}
async componentDidMount(){
try {
const response = await axios.get(`https://api.hatchways.io/assessment/students`);
this.setState({
students: response.data.students
})
} catch(error){
alert('Wrong Json data from url')
}
}
handleChange(e){
if(e.target.value){
const dataSearch = this.state.students.filter(item => {
return item.firstName.toLowerCase().includes(e.target.value.toLowerCase())|| item.lastName.toLowerCase().includes(e.target.value.toLowerCase())
})
this.setState({
students: dataSearch
})
} else if (!e.target.value){
const initialData = this.state.students
console.log(initialData)
this.setState({
students: initialData
})
}
}
render(){
const elements = this.state.students.map((student) => {
const studentGrades = student.grades;
const sum = studentGrades.map(Number)
let sumGradeOfStudent = sum.reduce((a, b) =>(a + b) / sum.length )
return (
<div key={student.id} className="data-container">
<div className="image">
<img src={student.pic} alt="student-pics"/>
</div>
<div className="data-wrapper">
<h3>{student.firstName} {student.lastName}</h3>
<p>Email:{student.email} </p>
<p>Company:{student.company} </p>
<p>Skill:{student.skill}</p>
<p>Average: {sumGradeOfStudent.toFixed(2)}%</p>
<hr />
</div>
</div>
);
})
return (
<div>
<InputField input={this.state.input} handleChange={this.handleChange} />
{elements}
</div>
)
}
}```
if you can take a Look at the handleChange method. after setting state the first time. I am trying to set it again inside the else if statement when the value in the input target is false. so I created a new variable and set it to the state. but it doesn't work, if you look at my console.log, I don't get the full items in the states([]), what I get is a fraction of what changed during the first time the state was initialized when the handleChange method was initialized.
I also tried making A shallow copy of the state by using slice, because I saw from StackOverflow that the difference between the old and the new state won't be detected.
still yet It still doesn't work. I have been on this for a few days now. if anyone can point me to the right direction I will appreciate it or take a look at it and tell me where I'm making an error. I look forward to a response please.