Dennis-b
Dennis-b

Reputation: 121

React SWR, how to filter/sort data

I have typical get request

const { data } = useSWR(
  ['api/projects', API_KEY],
  fetcher
);

And after fetching data I would like to filter items, in my case based on current GPS location. So how is better to make this? Like onSuccess(data, key, config) store data to my state and after work on filtering? Or I should use mutations somehow and filter cached data?

Upvotes: 8

Views: 4473

Answers (1)

Yaroslav Bigus
Yaroslav Bigus

Reputation: 678

You can simply filter data into a new array and render component basing on this array. Something like this:

const { data:projects, error } = useSWR(
    ['api/projects', API_KEY],
    fetcher
);
if(error) return (<ErrorScreen />);
if(!data) return (<Loading />);
let availableProjects = projects.filter(p => availabilityChecker(p.location));
return (
    availableProjects.map(p => (<Project key={p.id} project={p} />));
);

Upvotes: 1

Related Questions