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>
}
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.