I am new to react. I was working on a small project. I am having to display a table(listFeatures.js) and rows can be added to the table via a form submission(addTech.js). But the state change is not being reflected. I probably feel useEffect() can help me in this case but I don't know how to use it properly. Can someone please help...
Code given below
app.js
import React, { useState, useEffect } from 'react'
import ListFeatures from './components/ListFeatures/listFeatures'
import AddTech from './components/AddTech/addTech'
const App = () => {
const [resourceType, setResourceType] = useState('posts')
const [tech, setTech] = useState({
t_names: ["Java", "Python", "C++"],
feature: [
{
name: "Speed",
feat_list: [
{desc: "fast", score: 7},
{desc: "slow", score: 5},
{desc: "very fast", score: 9}
]
},
{
name: "Complexity",
feat_list: [
{desc: "High", score: 3},
{desc: "Low", score: 8},
{desc: "Medium", score: 6}
]
},
{
name: "Modulartiy",
feat_list: [
{desc: "medium", score: 7},
{desc: "Low", score: 6},
{desc: "High", score: 9}
]
},
],
})
const AddNewTechHandler = (newTech) => {
const newTable = tech
newTable.t_names.push(newTech.t_names)
newTable.feature.map((feat, index) => {
feat.feat_list.push(newTech.feature[index])
})
setTech(newTable)
console.log(tech)
// This console.log shows tech being updated but the changes are not reflected.
}
return (
<div className = "container">
<AddTech onAddTech = {AddNewTechHandler}/>
<ListFeatures tech = {tech} />
</div>
)
}
export default App
listFeatures.js
import React from 'react'
const ListFeatures = (props) => {
return (
<table>
<tr>
<th></th>
{
props.tech.t_names.map((tech) => {
return (
<React.Fragment>
<th> {tech} </th>
<th></th>
</React.Fragment>
)
})
}
</tr>
{
props.tech.feature.map((techs) => {
return(
<tbody>
<tr>
<td>{techs.name}</td>
{
techs.feat_list.map((feature) => {
return(
<React.Fragment>
<td>{feature.desc}</td>
<td>{feature.score}</td>
</React.Fragment>
)
})
}
</tr>
</tbody>
)
})
}
</table>
)
}
export default ListFeatures
addTech.js
import React, { useState } from 'react'
const tech_list = ['Python', 'Java', 'C++', 'JS'];
const AddTech = (props) => {
const [techChosen, setTechChosen] = useState('')
const addTechHandler = event => {
event.preventDefault();
console.log("Is this working ?")
console.log(techChosen)
const newTech = {
// There will be an api call over here in the future.. for now dummy value.
t_names: "Js",
feature: [
{
desc: "fast",
score: 8,
},
{
desc: "High",
score: 2
},
{
desc: "medium",
score: 8
},
],
}
props.onAddTech(newTech);
}
const optionChangeHandler = event => {
setTechChosen(event.target.value);
}
return (
<div className = "container">
<form onSubmit={addTechHandler}>
<label>Choose Tech</label>
<select name="tech" id="tech" onChange={optionChangeHandler}>
<option value="">Select a Tech</option>
{
tech_list.map((tech) => {
return(
<option value={tech}>{tech}</option>
)
})
}
</select>
<button type="submit">Add Tech</button>
</form>
</div>
);
};
export default AddTech;