DEV Community

Mohmed Ishak
Mohmed Ishak

Posted on

Cool Stuffs About Programming I Wish I Knew Earlier

Hey guys, have you ever stumbled upon cool tricks when programming and wondered how you lived without them? In this article, I'll show you a couple of cool tricks you might now know.

[1] Add Item To Beginning of Array in JavaScript

Using spread operator right? No. Turns out there's a cleaner way to add item to beginning of an array which is by using unshift method.

const arr = [2, 3, 4, 5];
const newArr = arr.unshift(1);

console.log(newArr); // output is [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

[2] Select Colors Like A Pro

To be honest with you, people judge your app heavily based on the UI and the color scheme you use (a lot of them don't care if you used message queue or sharded your database although these are important to build apps at scale). There's a site called Coolors (coolors.co) which generates you a lot of cool color palettes in no time so you don't have to pick random colors manually for your app which eventually you will mess up.
Alt Text

[3] Don't Call API Directly

Calling APIs directly might not be the best idea because it pollutes the codebase. Based on the frontend language/framework/library you're using, find out a way to create a generic function to call API and handle response/error from it. Here's an example of reusable Hook to call APIs in React Native (using Apisauce):

import { useState } from "react";

export default useApi = (apiFunc) => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(true);
  const [loading, setLoading] = useState(false);

  const request = async (...args) => {
    setLoading(true);
    const response = await apiFunc(...args);
    setLoading(false);

    setError(!response.ok);
    setData(response.data);
    return response;
  };

  return {
    data,
    error,
    loading,
    request,
  };
};
Enter fullscreen mode Exit fullscreen mode

Buy Me A Coffee

Top comments (0)