0

(component A is Home.jsx, component B is ChartSongs.jsx and component C is AudioPlayer.jsx)....... In component A I have an array of songs,then I passed it as props to component B

{/*The array*/}
chartData whose value was fetched from an array
{/*then i passed it as props to ChartSongs component*/}
  const songTitleEl = chartData.map((data, i) =>(
    <ChartSongs key={data.key} title={data.title} artiste={data.subtitle} coverarts={data.images?.coverart} index={i}/>
  ))

Then I shuffled the chartData array array using Fisher Yates algorithm in component C NOTE: I'm using context API to pass chartData around my components

function shuffle(arr){
  for (let i = arr.length; i > 0; i--){
    const j = Math.floor(Math.random() * (i + 1));
    const temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp; 
  }
  return arr;
}

Then I proceeded to updating chartData to the shuffled array with a function

 function playShuffle(){
  setChartData(shuffle(chartData))
 }

But I got this error when playShuffle() function runs

Uncaught TypeError: Cannot read properties of undefined (reading 'title')
    at Home.jsx:74:44
    at Array.map (<anonymous>)
    at Home (Home.jsx:73:33)
    at renderWithHooks (react-dom.development.js:16305:18)
    at updateFunctionComponent (react-dom.development.js:19588:20)
    at beginWork (react-dom.development.js:21601:16)
    at beginWork$1 (react-dom.development.js:27426:14)
    at performUnitOfWork (react-dom.development.js:26557:12)
    at workLoopSync (react-dom.development.js:26466:5)
    at renderRootSync (react-dom.development.js:26434:7)

I'm developing a music app and i want to add a shuffle feature to my audio player. How do i resolve this?

NOTE: This is what the chartData array looks like

enter image description here

Tomiwa
  • 59
  • 7

1 Answers1

0

try it like this title={data?.title}

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
  • [A code-only answer is not high quality](//meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation. – Stephen Ostermiller Nov 29 '22 at 15:37