Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
Show filtered result from api in React/Typescript

I have a component that fetches data and then I am setting that data via state. If I want to filter that data based on certain criteria or fields from the api, would I do the filter method? or is this not advisable for state objects?

https://stackblitz.com/edit/react-x7tlxr?file=src/App.js

So far I am doing this: but it's not working as the filtering does not happen.

const [fetchData, setFetchData] = React.useState<any>([]);
const [loading, setLoading] = React.useState<boolean>(true);
const [isError, setIsError] = React.useState<boolean>(false);

const url: string = 'https://xxxxxx';

useEffect(() => {
    let mounted = true;
    const loadData = async (): Promise<any> => {
        try {
            const response = await axios(url);
            if (mounted) {
                setFetchData(response.data);
                setLoading(false);
                setIsError(false);
                console.log('data mounted')
            }
        } catch (err) {
            setIsError(true)
            setLoading(false);
            setFetchData([]);
            console.log(err);
        }
    };
    loadData();
    return () => {
        mounted = false;
        console.log('cleaned');
    };
},
    [url]
);

function to filter based on onClick:

onClick={(idx: number) => {
    const resultInnerNew = fetchData.filter((statusPoint: any) => statusPoint.status === 'New');
    setFetchData(resultInnerNew)
}

binding to template:

   {isError ? <p className="mt-5">There is an error fetching the data!</p> : <div className="container"></div>}
   {loading ? <div>Loading ...</div> : <div className="cards row card-container mt-5">
   // data here
   </div>
   }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could use an arrow function to update the state and filter the data as below,

onClick={(idx: number) => {
    setFetchData(data => data.filter(statusPoint => statusPoint.status === 'New')
}}

A quick review on Array.prototype.filter(), this code will only keep the values which have statusPoint.status equal to 'New' in your array.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda