Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Reaccionar: agregar búsqueda a una tabla, ¿forma correcta?

Agregué una función de búsqueda para mi tabla en React para filtrar elementos obtenidos de un servicio web externo. Como no quiero llamar a la API cada vez que busque un proyecto, pensé que asignaría los datos recuperados a dos ganchos useState diferentes.

Uno para contener el conjunto de datos completo y el otro para contener los elementos filtrados según la búsqueda.

¿Podría escribir un código más limpio sin usar 2 ganchos? ¿Algún efecto secundario de la forma en que el código maneja esto?

Cualquier entrada es apreciada.

 import React, { useState, useEffect } from 'react'; import axios from 'axios'; import Table from '@mui/material/Table'; import TableHead from '@mui/material/TableHead'; import TableBody from '@mui/material/TableBody'; import TableRow from '@mui/material/TableRow'; import TableCell from '@mui/material/TableCell'; import DeleteIcon from '@mui/icons-material/Delete'; import TextField from '@mui/material/TextField'; export default function ShowProject() { const [data, setData] = useState([]); const [filter, setFilter] = useState([]) useEffect(() => { const fetchData = async () => { const result = await axios( 'http://127.0.0.1:5000/pr' ); setData(result.data); setFilter(result.data); } fetchData() }, []); const requestSearch = (searchedVal) => { const filteredRows = data.filter((row) => { return row.customer.toString().toLowerCase().includes(searchedVal.toString().toLowerCase()); }); if (searchedVal.length < 1) { setFilter(data) } else { setFilter(filteredRows) } }; return ( <div> <div> <TextField onChange={(e) => requestSearch(e.target.value)} /> <Table> <TableHead> <TableRow> <TableCell>Project</TableCell> <TableCell>Code</TableCell> <TableCell>Customer</TableCell> <TableCell></TableCell> </TableRow> </TableHead> <TableBody> {filter.map(item => ( <TableRow key={item.db_id}> <TableCell>{item.project_name}</TableCell> <TableCell>{item.project_code}</TableCell> <TableCell>{item.customer}</TableCell> <TableCell><DeleteIcon /></TableCell> </TableRow> ))} </TableBody> </Table> </div> </div> ) }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No veo ninguna razón particular para usar la variable de estado del filter . Está escaneando data y asignando el resultado filtrado para filter cada vez que cambia su TextField , entonces, ¿por qué no filtrar directamente en JSX y, en su lugar, almacenar el texto de la consulta como estado? Más concretamente, algo como lo siguiente:

 const [searchedVal, setSearchedVal] = useState(""); return ( <div> <div> {/* simply set the query text here instead of triggering requestSearch */} <TextField onChange={(e) => setSearchedVal(e.target.value)} /> <Table> <TableHead> <TableRow> <TableCell>Project</TableCell> <TableCell>Code</TableCell> <TableCell>Customer</TableCell> <TableCell></TableCell> </TableRow> </TableHead> <TableBody> {data .filter((row) => // note that I've incorporated the searchedVal length check here !searchedVal.length || row.customer .toString() .toLowerCase() .includes(searchedVal.toString().toLowerCase()) ) .map((item) => ( <TableRow key={item.db_id}> <TableCell>{item.project_name}</TableCell> <TableCell>{item.project_code}</TableCell> <TableCell>{item.customer}</TableCell> <TableCell> <DeleteIcon /> </TableCell> </TableRow> ))} </TableBody> </Table> </div> </div> );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!