Sort using query params and refactor code