What is useContext and how to use it in react?

By Prajwal Haniya

Tech-letter #4 | December 29,2022

  1. What are promises in JavaScript?

    Promises are one of the important concepts that you need to understand to write not only advanced JavaScript code but to write asynchronous functions. As JavaScript is single-threaded, promises are significant in order to perform certain things without stopping the other process.

    There are two things you need to understand :

    • Producing code
    • Consuming code

    The producing code is nothing but the code that takes a little bit of time to perform its task. For example, an API call may take little time to get a response from the backend(In the backend a promise will either resolve or reject). So the API call is the producing code. The code which depends on the producing code is called the consuming code. For example, .then() is performed once you get the response from the backend, this is called the consuming code as it is dependent on the response.

    A promise is a JavaScript Object. It has three properties: Pending, Fulfilled (resolved), and rejected. When a promise is in the pending state the value of it is undefined , when it is in the fulfilled state the value is nothing but the result, and when the promise is in the reject state, the value will be an error object. A separate Promise() method must be used to handle the promises.

    A simple example of what a promise looks like is:

    const myFunction = new Promise((resolve, reject) => {
    //producing code
    	let count = 2;
    	if (count == 2) {
            resolve("Success");
    	} else {
            reject("error");
    	}
    });
    
    // consuming code
    myFuntion.then(res => console.log(res));
    

    For a deeper understanding of promises refer to this doc.

  2. What is useContext and how to use it in react?

    useContext helps you pass the data without using the props. This is one of the important concepts which you must know in order to build a login system. It’s not only limited to a login system but it’s required while implementing it.

    How and where to use this?

    The first step is to create the context object. Below I demonstrate a complete code of how you can authenticate a user that is from a firebase authentication with react js.

    Here, I have written two important functions, one is to login and the other is to logout.

    Both these functions can be triggered by any of the components without you manually passing them as props to each component or subcomponent. You just need to import them in the respective component. Whenever you modify something maybe a state, because you logged in, can update the state wherever it is imported.

    For example, once you login, you will be redirected to protected routes. The protected routes are accessible only if you are logged in. But, imagine you are inside a protected route and you will logout quickly by clicking the logout button in the header component. Then for the next action you must not be able to access other protected routes, so how will you achieve this? So to achieve this you need the concept of context in react.

    import { signInWithEmailAndPassword, signOut } from "firebase/auth";
    import { createContext, useContext, useEffect, useState } from "react";
    import { auth } from '../utils/firebase';
    
    const AuthContext = createContext();
    
    export const useAuth = () => {
        return useContext(AuthContext);
    }
    
    export const AuthProvider = ({ children }) => {
        const [currentUser, setCurrentUser] = useState();
        const [userLoading, setUserLoading] = useState(false);
    
        const logIn = (email, password) => {
            setUserLoading(true);
            signInWithEmailAndPassword(auth, email, password).then(user => {
                setUserLoading(false);
                setCurrentUser(user);
            })
        } 
    
        const logOut = () => {
            signOut(auth);
            setUserLoading(false);
        }
    
        const value = {
            currentUser,
            userLoading,
            logIn,
            logOut
        }
    
        useEffect(() => {
        const unsubscribe = auth.onAuthStateChanged(user => {
                setCurrentUser(user);
            })
            return unsubscribe;
        }, []);
    
        return (
            <AuthContext.Provider value={value}>
                // you will be passing all the routes/components as a children 
                {children}
            </AuthContext.Provider>
        );
    }
    

    The value that you will be passing to the context provider is the one through which you can access all the states and functions in another component. There is one more step that you need add, you need to pack all the components with an AuthProvider as shown below so that you can access all the states and functions that yo have passed.

    function App() {
      return (
          <div className="App">
                // pack with <AuthProvider>
            <AuthProvider> 
              <Router>
                <Routes>
                  <Route path="/" element={<PrivateRoutes />}>
                     // all your private routes
                  </Route>
                  <Route path="/login" element={<LoginComponent />} />
                </Routes>
              </Router>
            </AuthProvider>
          </div>
      );
    }
    
    export default App;
    
  3. How to install PostgreSQL & pgadmin in ubuntu 20.04?

    Recently I have installed the same for an application that I am developing. I followed the below steps in order to install the PostgreSQL in my ubuntu system.

    Installation

    • sudo apt-get install postgresql

    Starting the database

    • systemctl start postgresql

    Next step is to install the pgadmin for a GUI based operation of a postgresql database

    1. Add pgadmin repo
    sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list'
    
    1. Add public key
    sudo curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add
    
    1. Update ubuntu

      sudo apt update && sudo apt upgrade

    2. Install pgadmin

      sudo apt install pgadmin4

    If you need the config file:

    sudo nano /etc/postgresql/12/main/postgresql.conf
    

    Make sure to alter the password:
    ALTER USER postgres PASSWORD ‘root’;

    Then go to the pgadmin → register the server → with the following details:

    • Host name/address: localhost
    • username: postgres
    • password: root / any password that you have provided.
  4. How to get the date in the dd-mmm-yyyy and 24hr time in JavaScript?

    Pass the date and time string in the function getDateAndTime. function below takes in the date and time & will return you the date-month-year (28-Dec-2022 21:19).

    You can use many such libraries which have some advanced levels of date & time manipulations. But for simplicity, if you want the date & time in the above format you can use the below function.

    const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    const getDateAndTime = (str) => {
         let now = new Date(str);
         let completeDateAndTime = '';
         const postDate = now.getDate() + '-' + monthNames[now.getMonth()] + '-' + now.getFullYear();
         const postTime = now.getHours() + ':' + now.getMinutes();
    
         completeDateAndTime = postDate + ' ' + postTime;
         return completeDateAndTime;
     }