Search code examples
reactjsarraysfisher-yates-shuffle

How can I update state in a component when the same state is passed as props in another component?


(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


Solution

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