I have been working on this issue for hours but I can't work out what the problem is.
I'm working on a React app which fetches an array of data from an API, but it seems like the array in the component which fetches the data is being affected by a shuffle function in a completely separate component.
It's hard to explain so here's some (simplified, but essentially the same) bits of code:
The fetch bit in Header.js:
fetch("https://example.com")
.then(result => return result.json())
.then(data => {
console.log(data)
this.props.updateData(data)
})
Main.js
class Main extends React.Component {
constructor(props) {
super(props)
this.state = {
currentData: []
}
this.updateData.bind(this)
}
updateData(data) {
this.setState({currentData: data)}
}
render() {
return(
<Header updateData={this.updateData} />
<Body data={data} />
)
}
}
The render bit of Body.js
render() {
return (
{shuffle(this.props.data).map(item => <p>{item.text}</p>}
)
}
The shuffle() function
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
The console.log in header.js sends the value of shuffle(data) to the console when that should only be run in body.js after being passed through main.js
Sorry if it makes no sense but I have searched for ages and I need to move on soon
Thanks in advance <3
shuffle()in the<Body />is theconsole.log()in<Header />as expected? seems like it might be a reference issueshuffle(this.props.data.map(item => <p>{item.text}</p>))result => return ...or missing)s