Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Organizer Refactor - New useSWR hooks and abstraction #360

Merged
merged 30 commits into from
Sep 13, 2023

Conversation

jacoblurie29
Copy link
Collaborator

@jacoblurie29 jacoblurie29 commented Sep 7, 2023

Organizer Refactor PR

This PR abstracts each tab of the organizer into its own file and creates a new reusable react hook to handle the useSWR function.

useCustomSWR

In request-utils.ts the following function is defined. It simplifies the use of the useSWR function by taking the url, request type, and error message as input params and a generic type T. The type T is the interface for the returned data.

export const useCustomSWR = <T>(params: CustomerSWRParams) => {
	const [data, setData] = useState<T[] | null>(null);
	const [error, setError] = useState<ResponseError | null>(null);

	const { data: requestData, error: requestError } = useSWR(params.url, async url => {
		const res = await fetch(url, { method: params.method });
		if (!res.ok) {
			const error = new Error(
				params.errorMessage || 'An error occurred while fetching data from the server.'
			) as ResponseError;
			error.status = res.status;
			throw error;
		}
		return (await res.json()) as T[];
	});

	useEffect(() => {
		if (requestData) {
			setData(requestData);
		}
		if (requestError) {
			setError(requestError);
		}
	}, [requestData, requestError]);

	return { data, error };
};

Example of useCustomSWR:

// Teams data
const { data: teamsData, error: teamsError } = useCustomSWR<TeamData>({
  url: '/api/teams',
  method: RequestType.GET,
  errorMessage: 'Failed to get list of teams.',
});

This can be used to replace any useSWR hook as it will simplify code, remove redundancy, and shorten the length of many files.

Refactoring

The Organizer.tsx file was refactored to abstract all of the tabs into individual components. Those components now load their own data as opposed to the web page loading the data and passing the data down through the props.

Much of the null checks, loading, and errors are combined to simplify the logic of the UI in statements like this:

// Combine all the loading, null, and error states
const error = teamsError || scoresError || judgeError;
const dataNull = !teamsData || !scoresData || !judgeData;

This allows the tabs to be generically formatted as so:

<>
    {dataNull ? (
        <div>Loading...</div>
    ) : error ? (
        <div>Failed to load data.</div>
    ) : (
        <AllScores teamData={teamsData} scoreData={scoresData} userData={judgeData} />
    )}
</>

@vercel
Copy link

vercel bot commented Sep 7, 2023

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
witness ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 12, 2023 11:51pm

…date as well will have to investigate in future
@jacoblurie29
Copy link
Collaborator Author

Was looking to update the "swr" package to >v2.0.0 because it supports an "isLoading" flag however the "next-auth" package current version (which is also old) relies on the properties of "swr" v1.3.0. Therefore I am unable to update either. I have a work around in to simulate loading (null data check) but it is not a true "loading" flag.

Copy link
Collaborator Author

@jacoblurie29 jacoblurie29 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a couple tiny changes. Great work!!!!

components/Organizer/ManageUsersTab/ManageUsersTab.tsx Outdated Show resolved Hide resolved
components/Organizer/PreAddUsersTab/PreAddUsersTab.tsx Outdated Show resolved Hide resolved
@jacoblurie29 jacoblurie29 changed the title Organizer Refactor Organizer Refactor - New useSWR hooks and abstraction Sep 12, 2023
@zineanteoh
Copy link
Member

LGTM. Probably the cleanest refactor I've ever seen. Proud of yall @lisaliuu @jacoblurie29 🔥

We went from >400 lines of code to just this
image

@zineanteoh zineanteoh marked this pull request as ready for review September 12, 2023 23:35
Copy link
Member

@zineanteoh zineanteoh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work @lisaliuu @jacoblurie29 !!

Our codebase is now so much more readable 🥲

@zineanteoh zineanteoh merged commit 582ce10 into main Sep 13, 2023
5 checks passed
@zineanteoh zineanteoh deleted the organizer-refactor branch September 13, 2023 03:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants