0

Estoy tratando de filtrar las clínicas por su provincia, pero al presionar el botón de búsqueda me devuelve la lista completa sin filtrar el valor del input. No logro ver donde esta el error en mi código. Las clínicas vienen de una api externa y busco obtener el resultado una vez filtrado, es decir, que no aparezca la lista completa en un principio, solo el resultado.

import React,  { useState, useEffect } from 'react'
import { getClinic } from '../../api/drupalAPI'
import {Clinic} from '@icofcv/common';
import Spinner from '../spinner/Spinner';



interface Props {
    showModalLocator: boolean,
    closeModalLocator: () => void
}


export const ClinicLocator: React.FC<Props> = ({ children, showModalLocator, closeModalLocator }) => {

    const [clinicList, setClinicList] = useState<Clinic[]>([]);
    const [clinicListFiltered, setClinicListFiltered] = useState<Clinic[]>([]);
    const [searchClinic, setSearchClinic] = useState("");


    const handleChange= (e) => {
        getClinic().then((response)=>{
            console.log(response)
            setClinicList(response);
            setClinicListFiltered(response)
        }).catch ( (error)  => {
            console.error(error);
            throw error;
        });
        setSearchClinic(e.target.value);
        filter(e.target.value);
      }
      
      const filter=(termSearch)=>{
        const resultSearch= clinicList.filter((element)=>{
          if(
          
           element.province?.toString().toLowerCase().includes(termSearch.toLowerCase())
        
          ){
            return element;
          }
        });
        setClinicListFiltered(resultSearch);
      }

    return (
        <>
              <div>
                {showModalLocator ? (
                    <>
                        <div className="justify-center items-center flex overflow-x-hidden overflow-y-auto fixed inset-0 z-50 outline-none focus:outline-none">
                            <div className="relative p-2 w-full max-w-3xl h-full md:h-auto">
                                {/*content*/}
                                <div className="relative bg-white rounded-lg shadow">
                                    {/*header*/}
                                    <div className="flex justify-between items-start px-4 py-3 rounded-t border-b">
                                        <h3 className="text-lg font-medium">Localizador de clinicas</h3>
                                        <button className="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center" onClick={closeModalLocator}>
                                            <svg aria-hidden="true" className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
                                                <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
                                            </svg>
                                        </button>
                                    </div>
                                    {/*body*/}
                                    <div className="relative px-3 py-3 flex-auto overflow-auto modal-body">
                                        <h2 className="text-sm font-medium mb-2">¿Dónde te encuentras?</h2>
                                        <input 
                                        value={searchClinic}
                                        onChange={(e) => setSearchClinic(e.target.value)}
                                        type="search" 
                                        className="w-100 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block p-2" 
                                        placeholder="Introduce una ubicación"
                                        />
                                        <div className="py-3 border-b flex flex-col md:flex-row items-start md:items-center md:justify-between justify-start gap-2">
                                            <div className="flex items-center">
                                                <label className="inline-flex relative items-center mr-5 cursor-pointer">
                                                    <input type="checkbox" className="sr-only peer" checked/>
                                                    <div className="w-11 h-6 bg-gray-200 rounded-full peer peer-focus:ring-teeal-600 
                                                    peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] 
                                                    after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-teal-600"></div>
                                                    <span className="ml-2 text-xs font-medium text-gray-900">Centro privado</span>
                                                </label>
                                            </div>
                                            <div className="flex items-center">
                                                <label className="inline-flex relative items-center mr-5 cursor-pointer">
                                                    <input type="checkbox" className="sr-only peer" readOnly/>
                                                    <div className="w-11 h-6 bg-gray-200 rounded-full peer peer-focus:ring-teeal-600 
                                                    peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] 
                                                    after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-teal-600"></div>
                                                    <span className="ml-2 text-xs font-medium text-gray-900">con Mútuas</span>
                                                </label>
                                            </div>
                                            <div className="flex items-center">
                                                <label className="inline-flex relative items-center mr-5 cursor-pointer">
                                                    <input type="checkbox" className="sr-only peer" readOnly/>
                                                    <div className="w-11 h-6 bg-gray-200 rounded-full peer peer-focus:ring-teeal-600 
                                                    peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] 
                                                    after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-teal-600"></div>
                                                    <span className="ml-2 text-xs font-medium text-gray-900">con Compañías de Salud</span>
                                                </label>
                                            </div>                                            
                                        </div>
                                        <div>
                                            <h2 className="text-sm font-medium my-3">Resultados</h2>
                                            <div className="w-100">
                                                <iframe className="w-100" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2664.3238269926374!2d-0.3805919350162851!3d39.46959682083709!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0xd604f4bee0957f3%3A0x6686ff7d230b3965!2zQy4gZGUgU2FudC
                                                BWaWNlbnQgTcOgcnRpciwgNjEsIHBpc28gMsK6LCBwdGEgMsKqLCA0NjAwMiBWYWzDqG5jaWEsIEVzcGHDsWE!5e0!3m2!1ses!2sus!4v1662388390673!5m2!1ses!2sus" loading="lazy"></iframe>
                                            </div>
                                            <div className="md:mt-4 overflow-auto relative py-2">
                                                <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                                                    <div className="card bg-white px-2 py-3 h-36 md:h-32">
                                                        {!clinicListFiltered ? <Spinner /> :
                                                            clinicListFiltered.map((clinic) => (
                                                        <button key={clinic.id} type="button" className="text-left">
                                                            <div className="flex items-center gap-2 md:gap-4 md:gap-4">
                                                                <img className="h-24 w-2/5 min-w-40 object-cover object-center rounded-lg" src="../carousel-1.svg" alt="#"/>
                                                                <div className="w-3/5">
                                                                    <div className="text-md font-medium leading-5 clinic-title uppercase">{clinic.title}</div>
                                                                    <div className="flex items-center gap-2">
                                                                        <div className="text-neutral-500 text-sm">{clinic.propsPhone}</div>
                                                                        <div className="text-neutral-500 text-sm">{clinic.mobile}</div>
                                                                    </div>
                                                                    <div className="text-teal-600 text-sm underline clinic-mail">{clinic.email}</div>
                                                                    <div className="text-neutral-500 text-sm">{clinic.registry}</div>
                                                                </div>
                                                            </div>
                                                        </button>
                                                            ))
                                                        }
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

1 respuesta 1

0

En React, los cambios no son inmediatos debido a la forma asincrona en que trabaja la biblioteca. Acá te dejo un artículo que lo deja más claro.

Aclarado este importantísimo punto, la solución sería manejar los valores ingresados en el input mediante useEffect

useEffect(() => {
   if (search.length > 0) {
      const filterList = data.filter(x => x.title.includes(search))
      setFilteredData(filterList)
   } else {
      setFilteredData(data)
   }
}, [search])

Lo que hace useEffect - en este caso - es ejecutar la función filter cada vez que ingresas un carácter en el input, y en caso que search no tenga nada, volvemos a mostrar todos los registros nuevamente.

Acá te dejo un ejemplo práctico. Si tienes dudas, comentarios u observaciones no dudes en comentarlas.

Saludos!

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.