0

I'm new to react and I want to create a list which can be sorted with price(salary). My api response is suppose -

[
    {
        "id":1,
        "name": "Person 1",
        "salary": 300
    },
    {
        "id":2,
        "name": "Person 2",
        "salary": 100
    },
    {
        "id":3,
        "name": "Person 3",
        "salary": 200
    }
]

I'm trying to use hooks useState and useEffect to get my data and populate the UI

const salary = () => {

    const [salaryState, setsalaryState] = useState([]);
    const [load, setLoad] = useState(false);
    const [geterror, setError] = useState('');

    useEffect(() => {
        axios.get('https://apiCall')
        .then(response => {
            setsalaryState(response.data);
            setLoad(true);
        })
        .catch(error => {
            setError(error.message);
            console.log('error', geterror);
        })
    },[]);

    const handleSalrySort = () => {
        var sortAsc = salaryState.sort((a,b) => {
            return parseFloat(a.salary) - parseFloat(b.salary)
        });
        setsalaryState(sortAsc);
        console.log('sortAsc', sortAsc);
    }

    if(load){
        return (
            <div className="container-fluid pt-3">
                <div onClick={handleSalrySort}>Salary - Low to High</div>
                {
                    salaryState.map((sal,index) => {
                        return(
                            <div>
                                Person : {sal.name}
                                Salary: {sal.salary}
                            </div>      
                        )
                    })
                }
            </div>
        )
    }else{
        return(
            <div></div>
        )
    }
}

Ater the handleSalrySort function I'm able to update the state salaryState but it's not reflecting on the UI. Can you please help me with that?

3 Answers 3

2

Array is reference type. hence, you need to get new copy of data by using map,slice etc. otherwise, React wont detect that data has changed as it points to same memory reference.

I have used slice() method. To sort in DESC order sort should should return b-a

 const handleSalrySort = () => {
    var sortAsc = salaryState.slice().sort((a, b) => {
      return parseFloat(b.salary) - parseFloat(a.salary);
    });
    setsalaryState(sortAsc);
    console.log("sortAsc", sortAsc);
  };
Sign up to request clarification or add additional context in comments.

Comments

0

Your code will work fine I didnt find any issues on that. Already the data in asc order only. So on click of that no changes detected. If still is not working please create the fiddle/sandbox link with appropriate data

For your reference, Demo

1 Comment

Sorry about that, shuffled the data a little bit
0

Try sorting your data in the then block of your axios call immediately after fetching it but before updating the state. Update the state in useEffect with an already sorted array of your data. It is more intuitive way to do it.

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.