I have below data
that I get from a json file and also import a utility function that picks out 5 random entities from an object Array in this case data
array which has 30 entities.
I'm struggling to render the 5 random jockies that are stored in unique
. I'm fairly new to the ES6 syntax. How can I render the 5 jockeys from unique
? Currently I'm getting
TypeError: Cannot read property 'avatar_url' of undefined
import * as React from 'react';
import { Jockey } from '../Jockey';
const data: JockeyArray[] = require('../../team.json');
import { getUniqueJockeys } from '../../utils/uniqueUtil';
interface JockeyArray {
id: number;
login: string;
avatar_url: string;
}
interface State {
nextRacers: string[];
jockeys: JockeyArray[];
}
export class Race extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
jockeys: data as JockeyArray[],
nextRacers: [],
};
}
render() {
if (this.props.startRandom) { // random selection
// returns data array as 5 unique entities
const unique = getUniqueJockeys(data);
console.log(unique);//I can see my 5 randoms generated.
return (
<div>
{ unique.map((racer, index) => (
// ??
<Jockey avatar={racer[index].avatar_url} />
))}
</div>
)
}
}
Definition of getUniqueJockeys
// Selecting 5 unique random jockeys
export const getUniqueJockeys = (anyArray: Array<object>) => {
let uniqueArray = [];
while (uniqueArray.length < 5) {
const unique = Math.floor(Math.random() * anyArray.length);
if (uniqueArray.indexOf(anyArray[unique]) > -1) {
continue;
}
uniqueArray.push(anyArray[unique]);
}
return uniqueArray;
};
You should change the definition of getUniqueJockeys
to be more generic. If data is of type JockeyArray[]
this should work (and you can use it for any values not just JockeyArray):
export const getUniqueJockeys = <T>(anyArray: Array<T>) => {
let uniqueArray: T[] = [];
while (uniqueArray.length < 5) {
const unique = Math.floor(Math.random() * anyArray.length);
if (uniqueArray.indexOf(anyArray[unique]) > -1) {
continue;
}
uniqueArray.push(anyArray[unique]);
}
return uniqueArray;
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments