-
-
Save pcast01/7de8b449f456d3685694c13af4acf52c to your computer and use it in GitHub Desktop.
A network request thing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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