So, I'm trying to sort my data into alphabetical order by location. What I have below seems to work, and my console log outputs the correct order - However, my component doesn't seem to re-render. I'm not sure whether it's simply not re-rendering, or if useEffect is kicking in and defaulting the sorting again? Pretty new to this, so I'm not entirely sure!
I've tried the below, with some simple text changes, and the app updates as expected.
Not sure sure where I'm going wrong?
Any help would be great. Thanks!
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios('/api/somestuff');
setData(result.data.default.sort((a,b) => a.brand.localeCompare(b.brand)));
};
fetchData();
}, []);
const sortLocation = () => {
setData(data.sort((a,b) => a.location.localeCompare(b.location)));
console.log(data)
}
return (
<>
<button onClick={() => sortLocation()}>Sort by location</button>
{data && data.map((item, index) => (
<span key={index}>
<p>{item.brand}</p>
<p>{item.location}</p>
</span>
))}
</>
);
}
export default App;