I’m trying to display data from an array in my React component.
I can see the data I need in the browser developer console from the console.log()
:
FinalRecords.js :: recordTitle: (4)
0: {members: Array(10), id: 62, title: 'RR 1980 Record 1', storeId: 1088}
1: {members: Array(10), id: 63, title: 'RR 1980 Record 2', storeId: 1088}
2: {members: Array(10), id: 64, title: 'RR 1980 Record 3', storeId: 1088}
3: {members: Array(10), id: 65, title: 'RR 1980 Record 4', storeId: 1088}
length: 4
[[Prototype]]: Array(0)
But I can’t seem to figure out how to get the title
.
I’ve tried a bunch of different things, with this one be the most recent:
render() {
const { recordId, records, bandName } = this.props;
var data = records.filter((r) => r.id === recordId);
var records = data.toArray();
console.log("FinalRecords.js :: recordTitle: ", records);
return <div> record - {findRecordTitle(records, recordId) } - {bandName || ''} </div>
}
}
function findRecordTitle(records, id) {
return records.find((record) => {
return record.id === id;
})
}
I need to get the title
of the record by using the id
.
But it just is always blank.
Is there something I’m doing wrong?
>Solution :
The name of this function implies that you expect it to return a "title" (which I would interpret as a string value):
function findRecordTitle(records, id) {
return records.find((record) => {
return record.id === id;
})
}
However, nothing in this function in any way references a "title". It returns a matching object from the records
array (or null
). If you want to return only a title
property from that object, just return that property:
function findRecordTitle(records, id) {
return records.find((record) => {
return record.id === id;
})?.title; // <--- here
}
Edit: In case your JavaScript environment can’t use optional chaining, you can explicitly check for null
before trying to use the object:
function findRecordTitle(records, id) {
const record = records.find((record) => {
return record.id === id;
});
return record ? record.title : null;
}
Or perhaps default to an empty string instead of null
, etc.