fix: only subscribe once to observables
This commit is contained in:
parent
6a37029e55
commit
2496bff82f
@ -3,7 +3,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { Observable, of } from 'rxjs';
|
import { Observable, of, tap } from 'rxjs';
|
||||||
|
|
||||||
const props = defineProps({
|
const props = defineProps({
|
||||||
name: {
|
name: {
|
||||||
@ -36,23 +36,21 @@ const isDataOutdated = (name: string): boolean => {
|
|||||||
const storeInCache = (
|
const storeInCache = (
|
||||||
callback: Function,
|
callback: Function,
|
||||||
data: any,
|
data: any,
|
||||||
name: string
|
name: string,
|
||||||
): Observable<any> => {
|
): Observable<any> => {
|
||||||
let response: Observable<any> = data ? of(data) : callback();
|
let response: Observable<any> = data ? of(data) : callback();
|
||||||
|
return response.pipe(
|
||||||
response.subscribe({
|
tap((response) => {
|
||||||
next: (response) => {
|
|
||||||
localStorage.setItem(name, JSON.stringify(response));
|
localStorage.setItem(name, JSON.stringify(response));
|
||||||
localStorage.setItem(name + '-timestamp', `${Date.now()}`);
|
localStorage.setItem(name + '-timestamp', `${Date.now()}`);
|
||||||
},
|
}),
|
||||||
});
|
);
|
||||||
return response;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (isDataOutdated(props.name)) {
|
if (isDataOutdated(props.name)) {
|
||||||
emits(
|
emits(
|
||||||
'cached',
|
'cached',
|
||||||
storeInCache(props.callback, props.alreadyKnownData, props.name)
|
storeInCache(props.callback, props.alreadyKnownData, props.name),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
let data = localStorage.getItem(props.name);
|
let data = localStorage.getItem(props.name);
|
||||||
@ -62,7 +60,7 @@ if (isDataOutdated(props.name)) {
|
|||||||
console.error(`Could not parse data found in cache: ${err}`);
|
console.error(`Could not parse data found in cache: ${err}`);
|
||||||
emits(
|
emits(
|
||||||
'cached',
|
'cached',
|
||||||
storeInCache(props.callback, props.alreadyKnownData, props.name)
|
storeInCache(props.callback, props.alreadyKnownData, props.name),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user