Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A network request thing
// useSearch file
import React, { useEffect } from "react";
import axios from "axios";
import { useImmerReducer } from "./useImmerState";
import { baseSelectedItems } from "../constants";
export function useSearch(selectedItems) {
function reducer(draft, action) {
switch (action.type) {
case "LOADING": {
draft.searchLoading = true;
return;
}
case "LOADED": {
draft.searchLoading = false;
draft.searchResults = action.data;
return;
}
}
}
const [search, dispatch] = useImmerReducer(reducer, {
searchLoading: false,
searchError: false,
searchResults: {}
});
useEffect(() => {
if (selectedItems.length > 0) {
dispatch({
type: "LOADING"
});
const currentItems = selectedItems.map(item => ({
type: "match",
field_key: item.field_key,
field_value: item.field_value
}));
axios
.post("/api/sherlock/v2/document/search", {
filters: [...baseSelectedItems, ...currentItems]
})
.then(({ data }) => {
dispatch({
type: "LOADED",
data
});
})
.catch(error => {
dispatch({
type: "ERROR"
});
});
}
}, [selectedItems]);
return { ...search };
}
// Using it elsewhere
function MyComponent() {
const { searchLoading, searchError, searchResults } = useSearch(
selectedItems
);
if (searchLoading) {
return <p>Loading<p>
}
if (searchError) {
return <p>Error</p>
}
// do something with results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.