Ways to create Forms in React

There are certain ways using which we can create Forms in ReactJS. One is using Class Components and another using Functional Components using Hooks.

Forms created using Class Component:

import React, { Component } from "react";

class Form extends Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default Form;

Forms can be created using React Hook Form – Functional Component

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = (data) => console.log(data);

  console.log(watch("example"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>

      <input name="exampleRequired" ref={register({ required: true })} />

      {errors.exampleRequired && <span>This field is required</span>}

      <input type="submit" />
    </form>
  );
}

Keep Creating!

Gardening in Quarantine

Doing something new has always inspired me. During the lockdown of Covid-19 Coronavirus pandemic, I tried again. This time, Gardening. Fresh vegetables, organic. The joy of seeing plant grow from nothing to something big is amazing.

I am sharing a video in the bottom of this post created from my garden. Along with my mother, I have been taking care of the vegetable garden. Have a look and let me know if it is exciting.

Fresh and Organic Lady Finger and Baby Snake Gourd
Fenugreek leaves fresh outta garden!
Check this video out!

Keep Eating, Folks 🥕

No, NoBroker.in, please

I am sharing this post about my recent interaction with a service provider in India called NoBroker. People often ask if they could trust a new company in the market. There are trust issues and there are incomplete service deliveries like in my case.

Is NoBroker Movers and Packers service good?

What was your experience with NoBroker Packers and Movers Service?

Nope.

Here’s my story.

1st September 2020 – It was one fine day when I got to know that NoBroker provides Packers and Movers Services. I contacted a couple of other Movers who had a nice reputation in the market. These Movers have their own fleet to move items from Source to Destination. They have strict timelines and nice support networks. After having a detailed conversation I decided to book my order through NoBroker. I had trust in your services because the company is doing well in Real Estate. Being from Bangalore and working in IT made me think to trust and take a chance.

2nd September 2020 – The next day I booked my assignment to be packed and picked up from Bangalore and sent to Indore. The pickup date was 2nd September 2020 4-6 PM slot. My items were picked up at 6 O’Clock. I was told that the vehicle is at Electronic City right now. It will take 50 minutes to reach my place. Although I already gave the vendor a call at Noon asking them to arrive by 5 because a person was available at that time at my location of pickup. And he was on a tight schedule because of the flight he needed to board later that evening. Finally, 3 items, 1 trolley, and 2 Medium-sized carton boxes were picked up from my place. And I was told that items will be sent to the courier (Gati) tonight for shipping. I paid the complete amount as asked by the Vendor –Protection Packers.

Status of ,my booking says Partner Assigned even today, 12th Sep, hilarious.

3rd September 2020 – The very next day, when I had no status anywhere, neither on the noBroker App Booking page nor from the vendor. Shoaib was my Move Manager and no doubt he has been doing everything he can to keep the customer happy. I got a positive reply from him and he will follow up with the vendor and let me know the status. I got a call from him stating the vendor has said that they will ship it today, 3rd September 2020. I was fine with it.

4th September 2020 – The next day when I did not get to hear from the vendor about tracking ID, I contacted them. Subhash who was assigned as the vendor partner picked up the call. He said they will do it today, 4th September 2020. The next day I tried to contact, I was told they will ship it today, 5th September 2020.

6th September 2020 – Similar incident happened on 6th when I contacted the vendor, he said he wants me to trust him. I have paid in advance for my task, I have been promised a TAT of 7 days. It doesn’t matter but I should have an update about where my belongings are. But the vendor was not ready to do it. After a lot of requests from Shoaib, he agreed to send the tracking number to me and to him. To my surprise, I found out that this Tracking Number was a lie.

10th September 2020 – I tweeted NoBroker for an update and they called and gave me the correct Tracking Number. Finally, my items are moving towards me.

I knew the team was doing everything they can to maintain good CSAT but vendors like the one assigned for my task are ruining it. When I was booking, I dreamt of Platinum Trusted Partners that you have mentioned on your website. I imagined Agarwal Packers and Movers picking up my items and shipping them. So I could have them in 7 days and be free. I was frustrated, exhausted following up every single day to get an update.

Trusted Partners section never mentioned that local packers will be assigned to do the job.

Disclaimer – This post is a personal user review of service provider, NoBroker. The views in this post are personal. These are based on experience of the paid services used by me. This review is specific to Packers & Movers Services.

Good Luck Moving with NoBroker.in 🤣

Podcasts I follow on Google Podcast

Podcast related to new technology has always excited me. I use Google Podcasts App to follow the best ones. On a lazy weekend or a busy work day, I play them and enjoy the talk of the expert speakers.

Some of the Podcasts I follow are:

Happy Listening 🎙

Guppy – development made easy

Guppy is an application manager and it helps in running tasks. This involves tasks which are run through terminal. For React application development, this tool can help in minimizing the time spent on writing commands in terminal.

It can npm start your app through it’s beautiful graphical user interface. It can help build the app using npm run build or eject it.

Following screenshot is from Guppy with project ItemsInStock I am currently working on. You can easily Turn On or Turn Off the development server and perform other tasks.

Guppy GUI for managing React App on the go easily.
It can help check for updates of dependencies used in the project and update them.

How to use Guppy? It’s simple. Just head on to https://github.com/joshwcomeau/guppy on GitHub and follow the instructions in README.md. Or you can directly go here and download it for PC or Mac https://github.com/joshwcomeau/guppy/releases

This tool is great for newcomers and beginners starting in ReactJS to ease their journey to become an expert developer.

Guppy was created by https://github.com/joshwcomeau – Joshua Comeau

Happy Guppy Day! 🦦

Immutable and Mutable Values

An immutable value is the one, which is once created can never be changed. Examples of immutable vales can be numbers, string and boolean.

Source element should not be affected and original element has to remain unchanged at all time.

While mutable values means changing the array or modifying the value. This is not recommended.

More here – https://medium.com/@fknussel/arrays-objects-and-mutations-6b23348b54aa

Peace

Fetch API in ReactJS Projects

The most basic thing I learned after fundamantals was using APIs in ReactJS. Although not easy, it took sometime to master its concepts. There are 3 ways to Fetch data from API:

  • Using Fetch with Lifecycle Method – componentDidMount in stateful/class component
  • Using Fetch with useState hook in stateless/functional component
  • Using Axios

AJAX call in componentDidMount

{
  "items": [
    { "id": 1, "name": "Apples",  "price": "$2" },
    { "id": 2, "name": "Peaches", "price": "$5" }
  ] 
}
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <ul>
          {items.map(item => (
            <li key={item.name}>
              {item.name} {item.price}
            </li>
          ))}
        </ul>
      );
    }
  }
}

AJAX call using Hooks in useEffect( ) hook

function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  // Note: the empty deps array [] means
  // this useEffect will run once
  // similar to componentDidMount()
  useEffect(() => {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result.items);
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {items.map(item => (
          <li key={item.name}>
            {item.name} {item.price}
          </li>
        ))}
      </ul>
    );
  }
}

Fetch request

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

Using Axios – GET Request

const axios = require('axios');
 
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });
 
// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  
 
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Using Axios – POST Request

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Keep Coding, Fellas!

Error – Expected an assignment or function call and instead saw an expression

Expected an assignment or function call and instead saw an expression is a common error whenever I forget adding return keyword to a function.

if(!loading) {
        return <p>Loading...</p>
    }
    else if (error) {
        <p>Some error occurred</p>
 //Error
    }

In the else if return statement, I missed the return keyword, causing this error.

if(!loading) {
        return <p>Loading...</p>
    }
    else if (error) {
        return <p>Some error occurred</p>
    }

Problem solved.