JavaScript/TypeScript
Linting
A lot of errors and style issues are caught when linters have been set
up properly. Commonly used are ESLint
and Prettier
. Most of the
required rules are already provided as a default, either with the
linter, or within the configuration file that came with the framework
used. When in doubt, consult the repository of a similar project or ask
a colleague.
Data Fetching & Request Handling
Data fetching & Request handling methods vary significantly between environments like Node.js and the browser. Each has its own unique methods and drawbacks. Native APIs can be inconsistent and behave differently across environments, they also do not integrate well with TypeScript’s type system, making it essential to use reliable libraries such as Axios.
Axios
Axios is the preferred choice for handling requests due to the following reasons:
- Interceptors: Provides middleware-like functionality that allows modifying
requests and responses before they are processed.
- Enables the addition of tokens/headers to requests
- Facilitates global error reporting on responses
- Consistency: Axios maintains consistent behavior across all JavaScript environments.
- TypeScript Support: Allows the use of generics with Axios, which wraps the Axios object data property, improving type safety.
- Automatic Serialization: Automatically serializes JavaScript data structures such as arrays, objects, and buffers, simplifying request payload handling.
SWR
SWR (stale-while-revalidate) is a popular asynchronous state management library for frontend applications,
particularly in React and Next.js.
It simplifies the handling of promise states (resolved, pending, rejected) with minimal abstraction.
SWR also provides automatic caching and on-demand cache invalidation through the mutate()
function,
enhancing project performance. SWR is best suited for data fetching requests, specifically “GET” requests.
SWR Example
Here is an example of how to use SWR in a React component:
const UserProfile = () => { // Use the useSWR hook const { data, error, isLoading, mutate } = useSWR("/user", fetcher);
if (isLoading) return <div>Loading...</div>; if (error) return <div>Error loading data</div>;
return ( <div> <h1>User Profile</h1> <p>Name: {data.name}</p> <p>Email: {data.email}</p> {/* Trigger a data refetch */} <button onClick={() => mutate()}>Update</button> </div> );};
In the example above the component handles different states (loading, error, and data) and renders the user profile accordingly. It also provides a direct way to manually refetch the data.