1

On my app I have a table that lists the names of employees, and I am currently able to click an "EXPAND ALL" button to display additional info for every employee at once. I am trying to implement a button that will expand and show that same info, but for only the one employee that is clicked on. I currently have an "EXPAND" button that console logs the info for that individual employee, but I can't figure out how to display it.

The component that renders all of the information

import { useState, useEffect } from "react"
// import { EmployeeForm } from "./EmployeeForm"


export function EmployeeTable() {
    const [employees, setEmployees] = useState([])
    const [employeeId, setEmployeeId] = useState([])
    const [update, setUpdate] = useState(false)
    const [expand, setExpand] = useState(false)
    const [expandSingle, setExpandSingle] = useState(false)

    const [firstName, setFirstName] = useState('')
    const [lastName, setLastName] = useState('')

    useEffect(() => {
      fetch('/api/employees')
      .then(res => res.json())
      .then(json => setEmployees(json.employees)
      )
      // console.log(expand)
    }, [])

    const expandAllEmployees = () => {
      if(expand === false) {
        setExpand(true)
      } if(expand === true) {
        setExpand(false)
      }
      console.log(expand)
    }

    const expandSingleEmployee = (email, phone, address, bio) => {
      if(expandSingle === false) {
        setExpandSingle(true)
        return(email, phone, address.streetAddress, address.city, address.state, address.zipCode, bio)
      } if(expandSingle === true) {
        setExpandSingle(false)
      }
      console.log(email, phone, address.streetAddress, address.city, address.state, address.zipCode, bio)
    }

    const updateEmployee = async () => {
      try {
      const res = await fetch(`/api/employees/${employeeId}`, 
      {method: 'PATCH', body: JSON.stringify({firstName, lastName})})
      const json = await res.json()

      const employeesCopy = [...employees]
      const index = employees.findIndex((employee) => employee.id === employeeId)
      employeesCopy[index] = json.employee

      setEmployees(employeesCopy)
      setFirstName('')
      setLastName('')
      setUpdate(false)
      setEmployeeId(null)
  } catch (err) {
      console.log(err)
  }
}

const submitForm = async (event) => {
  event.preventDefault()

  if(update){
      updateEmployee()
  }
}
    
  
const deleteEmployee = async (id) => {
  try {
      await fetch(`/api/employees/${id}`, {method: 'DELETE'})
      setEmployees(employees.filter(employee => employee.id !== id))
  } catch (error) {
      
  }
}
    const setEmployeeToUpdate = (id) => {
        const employee = employees.find(emp => emp.id === id)
        if(!employee) return
        setUpdate(true)
        setEmployeeId(employee.id)
        setFirstName(employee.firstName)
        setLastName(employee.lastName)
    }

    return (
        <div>
            <table>
              <tbody>
              <tr>
                <td>
                  <button onClick={() => expandAllEmployees()}>{expand ? 'COLLAPSE ALL' : 'EXPAND ALL'}
                </button>
                </td>
              </tr>
                {employees.filter(item => item).map(({id, avatar, firstName, lastName, email, phone, bio, address}) => {
                  return(
                    <tr key={id}>
                    <td><img src={avatar} alt="avatar" style={{height: '60px', width:'100px'}}/></td>
                    <td>{firstName}</td>
                    <td>{lastName}</td>
                    {expand === true ? (
                      <table>
                        <thead>
                          <tr>
                          <td>{email}</td>
                          <td>{phone}</td>
                          <td>{address.streetAddress}</td>
                          <td>{address.city}</td>
                          <td>{address.state}</td>
                          <td>{address.zipCode}</td>
                          <td>{bio}</td>                    
                          </tr>
                        </thead>
                      </table>
                    ) : (
                      <th></th>
                    )}
                    <td>
                        <button onClick={() => setEmployeeToUpdate(id)}>UPDATE</button>
                        <button onClick={() => deleteEmployee(id)}>DELETE</button> 
                        <button onClick={() => expandSingleEmployee(email, phone, address, bio)}>{expandSingle ? 'EXPAND' : 'COLLAPSE'}</button>                 
                    </td>
                  </tr>
                  )
                })}
              </tbody>
            </table>
                <form onSubmit={submitForm}>
            <div>
                <div>
                    <input type="text" value={firstName} onChange={e => setFirstName(e.target.value)}/>
                </div>
                <div>
                <input type="text" value={lastName} onChange={e => setLastName(e.target.value)}/>
                </div>
                <div>
                    <button type='submit'>{update ? 'Update' : 'Create'}</button>
                </div>
            </div>
        </form>
      </div>
      )
}

The server.js file

import { createServer, Model } from "miragejs";
import faker from "faker";
import avatar from "./avatar.png";

export function makeServer({ environment = "test" } = {}) {
  let server = createServer({
    environment,
    models: {
      employee: Model,
    },
    seeds(server) {
      for (let i = 0; i < 10; i++) {
        server.create("employee", {
          id: faker.datatype.uuid(),
          firstName: faker.name.firstName(),
          lastName: faker.name.lastName(),
          email: faker.internet.email(),
          phone: faker.phone.phoneNumber(),
          bio: faker.lorem.paragraph(),
          avatar: avatar,
          address: {
            streetAddress: `${faker.address.streetAddress()} ${faker.address.streetName()}`,
            city: faker.address.city(),
            state: faker.address.stateAbbr(),
            zipCode: faker.address.zipCode(),
          },
        });
      }
    },
    routes() {
      this.namespace = "api";
      this.get(
        "/employees",
        (schema) => {
          return schema.employees.all();
        },
        { timing: 1000 }
      );
      this.patch(
        "/employees/:id",
        (schema, request) => {
          const attrs = JSON.parse(request.requestBody);
          const employee = schema.employees.find(request.params.id);
          return employee.update(attrs);
        },
        { timing: 300 }
      );
      this.delete(
        "/employees/:id",
        (schema, request) => {
          const employee = schema.employees.find(request.params.id);
          employee.destroy();
          return new Response();
        },
        { timing: 300 }
      );
    },
  });
  return server;
}
Casey MacLeod
  • 31
  • 1
  • 6

1 Answers1

0

I'd recommend making expandSingle a Set of employee ids, and then you can check if that id is in the set. This allows you to both determine if a specific employee should be expanded, and also allows multiple employees to be expanded simultaneously.

Something like this:

const [expandSingle, setExpandSingle] = useState(Set())
const expandSingleEmployee = (id) => {
    if(expandSingle.has(id){
        expandSingle.delete(id);
    } else {
        expandSingle.add(id);
    }
}

And then for your conditional rendering:

{expand === true || expandSingle.has(id) ? (
  <table>
    <thead>
      <tr>
      <td>{email}</td>
      <td>{phone}</td>
      <td>{address.streetAddress}</td>
      <td>{address.city}</td>
      <td>{address.state}</td>
      <td>{address.zipCode}</td>
      <td>{bio}</td>                    
      </tr>
    </thead>
  </table>
) : (
  <th></th>
)}

And the expansion toggle:

<button onClick={() => expandSingleEmployee(id)}>{expandSingle.has(id) ? 'EXPAND' : 'COLLAPSE'}</button>
ChiefMcFrank
  • 721
  • 4
  • 18