I’m reviewing React state management, which I still find a bit confusing. This exercise comes from Colt Steele’s Advanced Coding Bootcamp on Udemy. The goal of this exercise is to list four instructors and their hobbies, and with a setTimeout of 5000ms, randomly remove one of the instructor’s hobbies. I randomly generate a number of one of the instructors on line 26. On line 29, I use the map function to loop through the array. When it comes to the randomly selected instructor, I randomly choose a hobby to remove. On line 40, I use setState to update the display.
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
instructors: [
{
name: 'Tim',
hobbies: ['sailing', 'react']
}, {
name: 'Matt',
hobbies: ['math', 'd3']
}, {
name: 'Colt',
hobbies: ['css', 'hiking']
}, {
name: 'Elie',
hobbies: ['music', 'es2015']
}
]
};
setTimeout(() => {
const randomNumber = Math.floor(Math.random() * this.state.instructors.length);
const randomHobbyNumber = Math.floor(Math.random() * this.state.instructors[randomNumber].hobbies.length);
const instructors = this.state.instructors.map((instructor, index) => {
console.log('randomNumber', randomNumber, 'randomHobbyNumber', randomHobbyNumber);
if (index === randomNumber) {
instructor.hobbies.splice(randomHobbyNumber,1);
console.log('instructor - delete hobby',instructor, index)
return instructor;
} else {
console.log('instructor',instructor, index)
return instructor;
}
});
this.setState({instructors})
},5000);
}
render() {
const instructors = this.state.instructors.map((instructor, index) => (
<li key={index}>
<h3>{instructor.name}</h3>
<h4>Hobbies: {instructor.hobbies.join(", ")}</h4>
</li>
));
return (
<div className="App">
<ul>
{instructors}
</ul>
</div>
);
}
}
export default App;