I'm new to MERN, so any help would be appreciated. Im trying to create a Stocks app. I have retrieved the data using axios and have displayed it in the table using Material-Table.
import React, {useState, useEffect} from 'react'
import MaterialTable from 'material-table'
import axios from "axios";
const DataTable = () => {
const [tableData, setTableData] = useState([]);
const columns = [
{title: 'NAME', field: 'name', width: 200},
{title: 'SYMBOL', field: 'symbol', width: 200},
{title: 'MARKET CAP', field: 'market_cap', width: 200},
{title: 'CURRENT PRICE', field: 'price', width: 200}
]
useEffect(() => {
axios
.get(
"https://api.nomics.com/v1/currencies/ticker?key=xyz&interval=1d,30d&convert=USD&per-page=100"`
)
.then((res) => {
console.log(res);
setTableData(res.data);
})
}, []);
return (
<div>
<div >
<MaterialTable style={{height: 400, width: '70%', left: '14%', top: 100}}
data={tableData}
columns={columns}
title={"Stock Details Table"}
options={{
search: true
}}
/>
</div>
</div>
)
}
export default DataTable
But now , i want to be able to save the row data of any company that i select into a mongoDb database and should be able to view all the companies that i selected.
My question is, how do i add a seperate column which has buttons for each company to enable me to add the row data into my mongodb database. I don't know how to add custom data along with the data from the api.
CodePudding user response:
According to the Material-Table documentation, there is a onClick
action property exist for the <MaterialTable>
component:
onClick: This event will be fired when the button is clicked. Parameters are
event
androw
orrows
So, you need to pass a function to onClick
property.
This function will get the row detail so you can post it to the server with another API call.
const handleSelectedRow = (event, row) => {
// console.log(row) to see the data and choose your require to send with API calling
axios.post("/saveMySelection", row).then(() => {}).catch(() => {}) // don't forget to use then and catch method with proper actions
}
<MaterialTable style={{height: 400, width: '70%', left: '14%', top: 100}}
data={tableData}
columns={columns}
title={"Stock Details Table"}
options={{
search: true
}}
actions={[
{
icon: 'save',
tooltip: 'Save User',
onClick: (event, rowData) => hadnleSelectedRow
}
]}
/>
You can also take a look at the first example of the working version on the documentation link that I mentioned earlier.