What I have to achieve is to show the data obtained as response from api in sorted order from first render itself.
This is how I'm using useEffect hooks:-
useEffect(()=>{
async function fetchProject() {
await axios.post(envurls.wv+'/show_project',{
params:{
authtoken:authtoken,
user:user
}
}).then((response)=>{
console.log('Res', response.data);
setShowProject(response.data)
}).catch((error)=>{
console.log(error)
})
}
fetchProject();
},[]);
useEffect(() => {
showProject.length> 0 && sortArray();
}, []);
const sortArray = ()=> {
const sortProperty = 'timestamp';
sorted = [...showProject].sort((a, b) => (a[sortProperty] > b[sortProperty] ? -1 : 1))
console.log("Project", showProject);
console.log("Sorted Data", sorted);
setShowProject(sorted);
};
But on first render, it is not sorting data as showProject array is empty. So, I'm getting Project and Sorted Data as empty array on console.
And If I provide showProject in useEffect like this:-
useEffect(() => {
showProject.length> 0 && sortArray();
}, [showProject]);
Then it is displaying sorted data for the first render itself but Project and Sorted Data are geetind displayed for n number of times in console.
showProjectthen it should be put into the dependency array. Also, you're not passing anything tosortArray