Skip to main content

Filtering data on the backend

By default data is filtered on the client side. To make the server-side filtering possible, in the example below, we do the following:

  • listen to the filter-files action and block it using the api.intercept method (and return false)
  • send the request for data to the /files?text route using the native fetch method
  • parse the received data via the provide-data action which is triggered by the api.exec method
  • set the mode value to search to parse data in this mode and return to the cards mode if there's no input
import { useState, useEffect } from "react";
import { Filemanager } from "@svar-ui/react-filemanager";

const server = "https://some-backend-url";

function parseDates(data) {
data.forEach((item) => {
if (item.date) item.date = new Date(item.date * 1000);
});
return data;
}

export default function App() {
const [rawData, setRawData] = useState([]);

useEffect(() => {
fetch(server + "/files")
.then((res) => res.json())
.then((data) => setRawData(parseDates(data)));
}, []);

function init(api) {
api.intercept("filter-files", (ev) => {
const { panels, activePanel } = api.getState();
const id = panels[activePanel].path;

fetch(
server +
"/files" +
(id === "/" ? "" : `/${encodeURIComponent(id)}`) +
`?text=${ev || ""}`
)
.then((res) => res.json())
.then((data) => {
api.exec("set-mode", { mode: ev ? "search" : "cards" });
api.exec("provide-data", {
id,
data: parseDates(data),
});
});

// block the default client-side filtering behavior
return false;
});
}

return <Filemanager init={init} data={rawData} />;
}

Related sample: Filtering on backend