Aug 03, 2020 08:27 PM
I am trying to get cell values of all fields of selected record Id. for now my current code only gets of a single field, any idea how its possible ?
import {initializeBlock, useBase, useRecords, useLoadable, useWatchable} from '@airtable/blocks/ui';
import React, {useState} from 'react';
import {cursor} from '@airtable/blocks'
function HelloWorldBlock() {
const [cellValue, setCellValue] = useState('')
useLoadable(cursor)
const base = useBase()
const table = base.getTableByName('Forex Cards')
const records = useRecords(table)
useWatchable(cursor, ['selectedRecordIds', 'selectedFieldIds'], () => {
if (cursor.selectedRecordIds.length > 0) {
const selectedId = records.find((value) => {
if (cursor.selectedRecordIds[0] === value._id) {
return value
}
})
setCellValue(selectedId.getCellValueAsString(cursor.selectedFieldIds))
}
})
return (
<div>
<div>{cellValue}</div>
</div>
)
}
initializeBlock(() => <HelloWorldBlock />);
Solved! Go to Solution.
Aug 04, 2020 12:14 PM
Hi @harshal,
To do this, you could iterate over the fields in the table, and use extract each cell value using Record.getCellValueAsString
for each field (like you’ve already got setup!). You could also pair this with useRecordById
to help with extracting the selected record:
useLoadable(cursor);
const base = useBase();
const table = base.getTableByName('Forex Cards');
const selectedRecord = useRecordById(table, cursor.selectedRecordIds[0] ?? '');
useWatchable(cursor, 'selectedRecordIds');
const [cellValuesByFieldName, setCellValuesByFieldName] = useState({});
useEffect(() => {
const newCellValuesByFieldName = {};
if (selectedRecord) {
for (const field of table.fields) {
newCellValuesByFieldName[field.name] = selectedRecord.getCellValue(field);
}
}
setCellValuesByFieldName(newCellValuesByFieldName);
}, [selectedRecord, table.fields]);
Aug 04, 2020 12:14 PM
Hi @harshal,
To do this, you could iterate over the fields in the table, and use extract each cell value using Record.getCellValueAsString
for each field (like you’ve already got setup!). You could also pair this with useRecordById
to help with extracting the selected record:
useLoadable(cursor);
const base = useBase();
const table = base.getTableByName('Forex Cards');
const selectedRecord = useRecordById(table, cursor.selectedRecordIds[0] ?? '');
useWatchable(cursor, 'selectedRecordIds');
const [cellValuesByFieldName, setCellValuesByFieldName] = useState({});
useEffect(() => {
const newCellValuesByFieldName = {};
if (selectedRecord) {
for (const field of table.fields) {
newCellValuesByFieldName[field.name] = selectedRecord.getCellValue(field);
}
}
setCellValuesByFieldName(newCellValuesByFieldName);
}, [selectedRecord, table.fields]);