2

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;

1 Answer 1

5

okay, sorting you are doing here is inplace sorting, so basically its the same array as before, as arrays are reference type is Javascript you need to create a new array to update the state, you can do as so

const sortLocation = () => {
    const dataArray = [ ...data]
    setData(dataArray.sort((a,b) => a.location.localeCompare(b.location)));
    console.log(data)
}

Hope it helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.