Master JavaScript with these slim, practical tips to make your code more efficient, readable, and maintainable.
Slim JavaScript Tips for Cleaner Code
Master JavaScript with these slim, practical tips to make your code more efficient, readable, and maintainable.
1. Use async/await for Asynchronous Requests
Why? Using
async/await
makes your code more readable and easier to maintain compared to
using
.then()
and
.catch().
Best Practice: Always use
async/await
syntax with Axios requests for better readability and error
handling.
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com');
console.log(response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
2. Handle Errors Gracefully
Why? Proper error handling ensures your app recovers gracefully from network issues or API errors.
Best Practice: Always use
try...catch
with
async/await
and leverage Axios error properties for debugging.
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com');
console.log(response.data);
} catch (error) {
if (error.response) {
// Server responded with a status other than 2xx
console.error('Server Error:', error.response);
} else if (error.request) {
// No response was received
console.error('Network Error:', error.request);
} else {
// Something went wrong while setting up the request
console.error('Error:', error.message);
}
}
};
3. Set Default Configuration for Common Requests
Why? Setting defaults prevents redundancy and keeps your code DRY (Don't Repeat Yourself).
Best Practice: Use Axios defaults to set common headers, base URLs, or other configurations.
axios.defaults.baseURL = 'https://api.example.com/';
axios.defaults.headers.common['Authorization'] = 'Bearer myAuthToken';
axios.defaults.headers.post['Content-Type'] = 'application/json';
4. Cancel Requests to Avoid Memory Leaks
Why? Canceling requests prevents memory leaks, especially in single-page apps.
Best Practice: Use
CancelToken
to cancel Axios requests when no longer needed.
const source = axios.CancelToken.source();
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data', {
cancelToken: source.token,
});
console.log(response.data);
} catch (error) {
if (axios.isCancel(error)) {
console.log('Request canceled: ', error.message);
} else {
console.error('Error: ', error);
}
}
};
// To cancel the request
source.cancel();
5. Throttle and Debounce Requests
Why? Throttling and debouncing minimize server requests, improving performance.
Best Practice: Use Lodash’s
_.debounce
or
_.throttle
to control request frequency.
const fetchData = _.debounce(async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log(response.data);
} catch (error) {
console.error(error);
}
}, 500);
6. Timeout for Requests
Why? Setting a timeout prevents your app from hanging due to network issues.
Best Practice: Use the
timeout
configuration to limit request duration.
axios.get('https://api.example.com/data', {
timeout: 5000, // Timeout after 5 seconds
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});
7. Use Response Data Transformation
Why? Transform response data when APIs return it in an unusable format.
Best Practice: Use
transformResponse
to modify data before use.
axios.get('https://api.example.com/data', {
transformResponse: [(data) => {
const parsedData = JSON.parse(data);
// Return only the 'items' from the response
return parsedData.items;
}]
})
.then(response => {
console.log(response.data); // Just 'items'
});
8. Use withCredentials for Cross-Domain Requests
Why? Send credentials like cookies for cross-domain requests.
Best Practice: Set
withCredentials
to
true
when needed.
axios.get('https://api.example.com/data', {
withCredentials: true, // Send cookies with the request
})
.then(response => {
console.log(response.data);
});

Comments
Post a Comment