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

192
Views
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 answers
Answer question

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 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!