I'm developing an application in react.Js
And I have a table that I need to update without having to refresh the page.
The code:
const App = () => {
const [item, setItem] = useState([])
const [category, setCategory] = useState([])
const categories = category.map(elem => ({
value: elem.id,
label: elem.cat,
}));
const [category_select, setCategorySelect] = React.useState(null);
function handleChangeCategory(value) {
setCategorySelect(value);
}
useEffect(() => {
getItems()
}, [])
useEffect(() => {
getCategories()
}, [])
const getItems = async () => {
const response = await axios.get(REQUEST_1)
setItem(response.data)
}
const getCategories = async () => {
const response = await axios.get(REQUEST_2)
setCategory(response.data)
}
const addItems = () => {
axios.post(`${REQUEST_1}`, {cat: category_select.value});
};
const body = () => {
return item && item.map((elem,j) => {
return (
<tr key={elem.id}>
<td><span>{elem.cat}</span></td>
</tr>
)
})
}
return (
<>
<div>
<div>
<div>
<div>
<NoSsr>
<Select
classes={classes}
styles={selectStyles}
inputId="category"
TextFieldProps={{
label: 'Category',
InputLabelProps: {
htmlFor: 'category',
shrink: true,
},
placeholder: 'Search',
}}
options={categories}
components={components}
value={category}
onChange={handleChangeCategory}
/>
</NoSsr>
<span>Select</span>
</div>
<div>
<label> </label>
<span onClick={addItems}></span>
</div>
</div>
<div>
<div>
<div>
<table>
<thead>
<tr>
<th>
<span>Category</span>
</th>
</tr>
</thead>
<tbody>
{body()}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</>
)
}
export default App;
The idea is that a category is selected and the item is added.
What I need is to be able to update the map (return item && item.map((elem,j) => {...})) after clicking on <span onClick={addItems}></span> which calls the addItems function that adds the item. Simply put I need it to be added in the table without having to update.
How can I do it, suggestions?