useEffect Part-2


In our last article, we have developed one Employee Component, which sends a Web API request, gets the list of employees and display them in a table.

Now we will extend that further. Assume that we have to implement one Auto Complete textbox in an application or we have to provide search capabilities to our Employee Data.

There will be a textbox using which we will enter employee name. As we keep entering the employee name, we have to send a request to our Web API, get the list of employees based on the search criteria and display the data in our Employee Component.

It is going to look like this.

This is very common requirement in most of the web applications.

First we will add the required functionality to our Web API.

public List<Employee> GetByName(string name)
        {
            if (name == null || name == "")
            {
                return empList;
            }
            else
            {
                return empList.Where(e => e.Name.Contains(name)).ToList();
            }
        }

Now lets open index.js file from our demo-project. We have developed the Employee Component in our last video. We will add the required changes to the same Component.

Lets add one state variable which will be holding search text.

Lets place the input element using which we will enter the search text. Add onChange attribute to the input element and call a function called as onSearchTextChange .

Lets implement the onSearchTextChange function.

When we are calling the Web API, we have to pass the name as well. Lets pass that search-text through the url. 

We wanted our code inside useEffect hook to be executed when the search text changes.

But empty [] tells react that we want that effect to be run only once.

This tells React that our effect doesn’t depend on any values from props or state, so it never needs to re-run.

But now we wanted useEffect hook to be executed when the state data changes.

We can pass the state variable as a dependency to our useEffect hook.

Save the changes, navigate to the browser. We can see that the table data changes based on our search text.

Our useEffect hook can have dependency on multiple state variables or properties as well.

For example, we can create another state variable called as employeeCount.

Lets place a button to add a new Employee. Assuming that on click of this button, we are adding a new employee. When the employee is created successfully, we get the number of employees and update the employeecount state variable. Now when there is a change in the count, we have to re-render our employee data.

That means the employees data should be re-rendered when the search text changes or when the employeecount changes. Now we will add employeesCount data also as a Dependency to our effect.

import ReactDOM from "react-dom";
import React, { Component, useState, useEffect } from "react";

function EmployeeComponent(){
  const [employees,setEmployees]=useState([]);
  const [searchText, setSearchText]=useState('');
  const [employeeCount, setEmployeeCount]=useState(0);
  
  useEffect(()=>{
    alert('We are inside useEffect Method');
    fetch("https://localhost:44306/api/Employee/"+searchText)
      .then(res => res.json())
      .then(
        (result) => {
          setEmployees(result);
        }
      );
  },[searchText,employeeCount]);

  function onSearchTextChange(e){
    setSearchText(e.target.value);
  }

  function addNewEmployee(){
    setEmployeeCount(employeeCount+1);
  }
  return(
    <div>
      <h2>Employees Data...</h2>
      <p>
        <label>Search By Name : <input type="text" value={searchText}
                                  onChange={onSearchTextChange}></input></label>
      </p>  
      <p>
        <button onClick={addNewEmployee}>Add Employee</button>
      </p>    
      <table>
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Location</th>
            <th>Salary</th>
          </tr>
        </thead>
        <tbody>
          {employees.map(emp=>(
            <tr key={emp.Id}>
              <td>{emp.Id}</td>
              <td>{emp.Name}</td>
              <td>{emp.Location}</td>
              <td>{emp.Salary}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}

const element=<EmployeeComponent></EmployeeComponent>

ReactDOM.render(element,document.getElementById("root"));

Video Reference:





© 2020 Pragimtech. All Rights Reserved.