Skip to content

Instantly share code, notes, and snippets.

@brunopk
Created November 5, 2020 16:03
Show Gist options
  • Save brunopk/20dda6ab38e804514a7c6af7f8d31acc to your computer and use it in GitHub Desktop.
Save brunopk/20dda6ab38e804514a7c6af7f8d31acc to your computer and use it in GitHub Desktop.
Custon hook to combine information from an HTTP service (using [useFetchSerial](https://snippets.cacher.io/snippet/881249469ca59cea7870)) and database (realm) in React Native
const useCombinedInfo = (id, combineInfo) => {
const {realm} = useContext(MainContext);
const [info, setInfo] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const [serviceInfo, serviceLoading, serviceError] = useFetchSerial(
[getResource],
[{id, filter}],
);
useEffect(() => {
if (serviceError) {
setIsError(true);
} else if (serviceLoading) {
setIsLoading(true);
} else if (serviceInfo === null) {
setIsError(false);
setIsLoading(false);
setInfo(null);
} else {
if (!combineInfo) {
setIsError(false);
setIsLoading(false);
setInfo(serviceInfo[0]);
} else {
setIsError(false);
try {
const realmFilter = 'attr1.id = %u AND attr2 = "%s"'
.replace('%u', id)
.replace('%s', 'someValue');
let dbResult = realm
.objects(Model.name)
.filtered(realmFilter);
setIsLoading(false);
setInfo(dbInfo.concat(serviceInfo[0]));
} catch (error) {
console.error(error);
setIsError(true);
setIsLoading(false);
}
}
}
}, [
serviceInfo,
realm,
serviceError,
serviceLoading,
combineInfo,
id,
]);
return [info, isLoading, isError];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment