Skip to content

Instantly share code, notes, and snippets.

@gtchakama
Created April 5, 2023 04:21
Show Gist options
  • Save gtchakama/d23c27fedae291e1d60c8befbbed1482 to your computer and use it in GitHub Desktop.
Save gtchakama/d23c27fedae291e1d60c8befbbed1482 to your computer and use it in GitHub Desktop.
Reactjs utility function that handles api calls in axios for login , signup , reset password and register
// api.ts
import axios, { AxiosResponse } from 'axios';
import apiConfig from './apiConfig';
// Define interfaces for request data types
interface LoginData {
email: string;
password: string;
}
interface SignUpData {
name: string;
email: string;
password: string;
}
interface ResetPasswordData {
email: string;
}
// Get the base URL and headers from the config module
const { BASE_URL, HEADERS } = apiConfig;
// Utility function for making POST requests
const postRequest = async <T>(url: string, data: Record<string, unknown>): Promise<T> => {
try {
const response: AxiosResponse<T> = await axios.post(`${BASE_URL}${url}`, data, { headers: HEADERS });
return response.data;
} catch (error) {
// Throw error response if available, or else the error message itself
throw error.response?.data ?? error.message;
}
};
// Export functions for each API endpoint
export const loginUser = async ({ email, password }: LoginData): Promise<unknown> => {
return postRequest('/login', { email, password });
};
export const signUpUser = async ({ name, email, password }: SignUpData): Promise<unknown> => {
return postRequest('/signup', { name, email, password });
};
export const resetPassword = async ({ email }: ResetPasswordData): Promise<unknown> => {
return postRequest('/reset-password', { email });
};
export const registerUser = async ({ name, email, password }: SignUpData): Promise<unknown> => {
return postRequest('/register', { name, email, password });
};
// apiConfig.ts
const BASE_URL: string = 'https://example.com/api';
const HEADERS: Record<string, string> = {
'Content-Type': 'application/json'
};
export default {
BASE_URL,
HEADERS
};
@gtchakama
Copy link
Author

In this file, we import the necessary modules and define interfaces for the different request data types. We then get the BASE_URL and HEADERS from the config module.

The postRequest() function is a utility function that takes in a URL and data object, and returns the response data from an Axios POST request. It has a generic type parameter for specifying the expected response data type. If there's an error, it throws either the error response or the error message itself.

Each of the API endpoint functions simply calls postRequest() with the desired endpoint URL and request data. They all have a return type of Promise since the specific response type is not known at compile time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment