I am working on page where I am showing data that are coming from API . Actually I am trying to display array data in reverse order but it not displaying data in reverse. when I refresh a page , first time data is displaying in reverse but after 3 seconds data is revert and display in original form . please help me thanks
Code
import React, { Component } from "react";
import DayPicker from "react-day-picker";
import "react-day-picker/lib/style.css";
import "./style.css";
import axios from "axios";
class DiarySideBar extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentWillMount() {
axios.get("/api/diary/all").then(res => {
this.setState({
data: res.data.rows
});
});
}
render() {
const { data } = this.state;
return (
<div>
<div className="calendarWrapper">
<DayPicker />
</div>
<div className="activeTaskMainWrapper">
<h6 className="activeTaskHeaderWrapper">Active Tasks</h6>
{data
.reverse()
.slice(0, 5)
.map(newData => (
<div className="activeTaskText">
<b>{newData.taskType}</b>
<p>{newData.subject}</p>
<hr />
</div>
))}
</div>
</div>
);
}
}
export default DiarySideBar;
The reverse function mutates the original array - that is your state variable and that can lead to the unexpected results.
Please clone the array before the reversal with the array spread operator [...data].reverse() or a slice call data.slice().reverse().
Edit: Since 2023 you can also use toReversed method to perform the reverse without affecting the original array. It makes a copy as a result instead of mutating the source.
Please use componentDidMount instead of componentWillMount
Try reversing logic in componentDidMount or a separate function instead of render function.
This way it would not re-render and go back to original order as you require.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With