GithubHelp home page GithubHelp logo

ngneat / query Goto Github PK

View Code? Open in Web Editor NEW
517.0 517.0 38.0 2.31 MB

๐Ÿš€ Powerful asynchronous state management, server-state utilities and data fetching for Angular Applications

Home Page: https://ngneat.github.io/query

TypeScript 81.69% JavaScript 1.73% HTML 15.98% SCSS 0.52% Shell 0.09%
async cache data fetch http pagination query stale-while-revalidate update

query's People

Contributors

arthie avatar aurelienlajoinie avatar cassilup avatar dalenguyen avatar donbabbeo avatar exflo avatar flaviodelgrosso avatar hrvbernardic avatar joaopaulolousada avatar luii avatar michaelxvoelker avatar netanelbasal avatar nitedani avatar pavankjadda avatar rskendzic avatar shaharkazaz avatar tieppt avatar trungvose avatar zacherl avatar zarghamkhandev avatar zbarbuto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

query's Issues

Implement Resource API

I was thinking about creating a nice abstraction named Resource, which encapsulates the key and keep it DRY, and also exposes other helpful methods to deal with entities. Here is my initial sketch:

class TodosService {
  todosResource = new Resource('todos');
  todoResource = new Resource<{ id: string }>(({ id }) => ['todo', id]);

  getTodos() {
     return this.todosResource.query(() => {
        return this.http.get('')
     })
  }

  addTodo(title: string) {
     return this.todosResource.mutate<Params>((params) => {
        return this.http.post('', params)
     }).pipe(
         tap(todo => {
           this.todosResource.addEntity() // need to think about the signature

        })
      )
  }

  removeTodo(title: string) {
     return this.todosResource.mutate<Params>((params) => {
        return this.http.delete('', params)
     }).pipe(
         tap(todo => {
           this.todosResource.removeEntity() // need to think about the signature
        })
      )
  }

  updateTodo(title: string) {
     return this.todosResource.mutate<Params>((params) => {
        return this.http.put('', params)
     }).pipe(
         tap(todo => {
           this.todosResource.updateEntity() // need to think about the signature
           this.todosResource.invalidate()
        })
      )
  }

  getTodo(id: string) {
    return this.todoResource.query({ id }, () => {
        return this.http.get(id);
    })
  }
}

Query won't refresh when new instances of the query mount

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

No

Description

Hi, I'm long time react-query user who recently join an angular development team. Very excited to see your library to come.
However, I noticed that query won't refresh when new instances of the query mount when I build my todos app demo here.

I use *ngIf to conditionally render todo list component. when the list component mounted again, the data in the cache showd in the component but no refetch is sending.

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in

No response

Anything else?

No response

Do you want to create a pull request?

No

Allow to pass observable as state keys

Which @ngneat/query-* package(s) are relevant/releated to the feature request?

No response

Description

If you use Tanstack Query in React world (useQuery(['posts', id], ()=>{})), state keys are being recalculated every id change together with data refetch.

@ngneat/query does not support this reactive recalculation. We should get new query for every new id:

import { UseQuery } from '@ngneat/query';

@Injectable({ providedIn: 'root' })
export class TodosService {
  private http = inject(HttpClient);
  private useQuery = inject(UseQuery);

  getTodo(id: number) {
    return this.useQuery(['todo', id], () => {
      return this.http.get<Todo>(
        `https://jsonplaceholder.typicode.com/todos/${id}`
      );
    });
  }
}

To provide reactive functionality, useQuery function should consume object with observable values and automatically refetch data on observable changes:

import { UseQuery } from '@ngneat/query';
import { Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class TodosService {
  private http = inject(HttpClient);
  private useQuery = inject(UseQuery);

  getTodoById(id$: Observable<number>) {
    return this.useQuery(['todo', {id: $id}], ({ id }) => {
      return this.http.get<Todo>(
        `https://jsonplaceholder.typicode.com/todos/${id}`
      );
    });
  }
}

Then inside component:

@Component()
export class TodosPageComponent {
  id$ = new BehaviorSubject(1) // signal(1)
  todos$ = inject(TodosService).getTodoById(this.id$)
}

Proposed solution

Add way to pass observable as state key and get them inside http query.

Alternatives considered

https://github.com/liaoliao666/react-query-kit

import { createQuery } from 'react-query-kit'

type Response = { title: string; content: string }
type Variables = { id: number }

const usePost = createQuery<Response, Variables, Error>({
  primaryKey: '/posts',
  queryFn: ({ queryKey: [primaryKey, variables] }) => {
    // primaryKey equals to '/posts'
    return fetch(`${primaryKey}/${variables.id}`).then(res => res.json())
  },
  suspense: true
})

const variables: Variables = { id: 1 }
export default function Page() {
  // queryKey equals to ['/posts', { id: 1 }]
  const { data } = usePost({ variables, suspense: true })

  return (
    <div>
      <div>{data?.title}</div>
      <div>{data?.content}</div>
    </div>
  )
}

Do you want to create a pull request?

No

Allow constructor injection for QueryClientService

Hi ๐Ÿ‘‹๐Ÿป,

thanks for working on this library. I really like the approach and the intuitive API.

Are there plans to support constructor-Injection for QueryClientService?
Currently, it does not work since it is an InjectionToken, which causes compilation errors (see images below).

Maybe QueryClient needs to be exposed as Public API.

Pure Constructor DI

image

@Inject-DI

image

Better support for constructor based injection for QueryClient, QueryProvider, MutationProvider and so on

Which @ngneat/query-* package(s) are relevant/releated to the feature request?

query

Description

The following right now is not possible:

@Injectable({ providedIn: 'root' })
export class TodosService {
  constructor(
    private http: HttpClient,
    private queryClient: QueryClient,
    private useQuery: QueryProvider,
    private useMutation: MutationProvider
  ) {}
}

cause of the error:

No suitable injection token for parameter 'queryClient' of class 'TodosService'.
  Consider using the @Inject decorator to specify an injection token.

The following also requires types:

@Injectable({ providedIn: 'root' })
export class TodosService {
  constructor(
    private http: HttpClient,
    @Inject(QueryClient) private queryClient: QueryClient,
    @Inject(QueryProvider) private useQuery: QueryProvider,
    @Inject(MutationProvider) private useMutation: MutationProvider
  ) {}
}

and fails with this error:

'QueryClient' refers to a value, but is being used as a type here. Did you mean 'typeof QueryClient'?ts(2749)

proposed typeof QueryClient doesn't work too cause of

Property 'invalidateQueries' does not exist on type 'InjectionToken<QueryClient>'.ts(2339)

Proposed solution

Not sure if there is a simple solution

Alternatives considered

The only solution that works for now is:

@Injectable({ providedIn: 'root' })
export class TodosService {
  private http = inject(HttpClient);
  private queryClient = inject(QueryClient);
  private useQuery = inject(QueryProvider);
  private useMutation = inject(MutationProvider);
}

Do you want to create a pull request?

No

Documentation navigation menu doesn't open on mobile

Which @ngneat/query-* package(s) are the source of the bug?

Don't known / other

Is this a regression?

Yes

Description

Pressing the menu button does nothing.
Screenshot_20230204-120836

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in

No response

Anything else?

No response

Do you want to create a pull request?

No

Optimize to leaner api

Which @ngneat/query-* package(s) are relevant/releated to the feature request?

query

Description

For any query or mutation you first need to inject a token and the use it, for example private useQuery = inject(UseQuery); and this.useQuery(...). This could be optimized by exporting a function which includes both lines.

Proposed solution

import { useQuery } from '@ngneat/query';

@Injectable({ providedIn: 'root' })
export class TodosService {
  private http = inject(HttpClient);

  getTodos() {
    return useQuery(['todos'], () => {
      return this.http.get<Todo[]>(
        'https://jsonplaceholder.typicode.com/todos'
      );
    });
  }

  getTodo(id: number) {
    return useQuery(['todo', id], () => {
      return this.http.get<Todo>(
        `https://jsonplaceholder.typicode.com/todos/${id}`
      );
    });
  }
}

Alternatives considered

Do you want to create a pull request?

No

Add examples to our playground

Which @ngneat/query-* package(s) are relevant/releated to the feature request?

No response

Description

Take one or more of the following examples, create an issue, and assign it to yourself:

Proposed solution

Alternatives considered

Do you want to create a pull request?

No

Rename QueryClient InjectionToken to QueryClientProvider

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

No

Description

I think it would wise to change the naming of the QueryClient InjectionToken to QueryClientProvider.
This way we can avoid the naming conflicts with the QueryClient in @tanstack/query-core package.

For now im importing both QueryClient types from @ngneat/query and @tanstack/query-core and rename the first one to get full verbose typing in my code

import {QueryClient} from "@tanstack/query-core";
import {QueryClient as QueryClientProvider} from '@ngneat/query'

class A {
  private readonly _queryClient: QueryClient = inject(QueryClientProvider)
}

I think this also makes sense since the QueryClient exported by @ngneat/query is a Injection Token and not an instantiatable Class.

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in

No response

Anything else?

No response

Do you want to create a pull request?

No

`result$` loses typing in the template

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

No

Description

I noticed that the result$ observable loses its typings and defaults to unkown in the template.
I tested this with my project and cloned the @ngneat/query repository and also checked it there.

The typing it should have
grafik

The typing it gets as soon it hits the template with async
grafik

Note: I used async here because using @ngneat/subscribe somehow doesnt unwrap the observable and gives me errors

Im not entirely sure what causes this but my guess would be the async pipe
with *subscribe this will happen:

grafik

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in

Tested in Webstorm 2022.3 Beta
Tested in Webstorm 2022.2.3 (Stable)
Visual Studio Code

Freshly cloned the `@ngneat/query` repository and install the dependencies with `npm install`

Anything else?

If the type is added explicitly there is no problem at all, only when omitting it.
So im not sure if its a problem with the angular/language-service or this package

Do you want to create a pull request?

No

Add operators

todos$ = this.todosService.getTodos().pipe(filterSuccess()),
todos$ = this.todosService.getTodos().pipe(filterError())
todos$ = this.todosService.getTodos().pipe(select(result => result.data.foo))

Add mapResultsData operator

Which @ngneat/query-* package(s) are relevant/releated to the feature request?

No response

Description

combineLatest([
  a$,
  b$
]).pipe(
  mapResultsData(([aData. bData]) => {
     return mappedData
  })
)

Proposed solution

combineLatest([
  a$,
  b$
]).pipe(
  mapResultsData(([aData. bData]) => {
     return mappedData
  })
)

Alternatives considered

No

Do you want to create a pull request?

No

provideQueryClientOptions changes behaviour of queries even when not changing any default properties

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

Yes

Description

If I use provideQueryClientOptions, and pass in an empty object, it changes the behaviour of the queries when it shouldn't.

Specifically, one of my queries is stuck in the "fetching" state

// app.module.ts

  provideQueryClientOptions({
      defaultOptions: {}
    })

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

My query is stuck in "fetching"

Please provide the environment you discovered this bug in

No response

Anything else?

No response

Do you want to create a pull request?

No

Prefetching example

Which @ngneat/query-* package(s) are relevant/releated to the feature request?

query

Description

Add prefetching example (https://tanstack.com/query/v4/docs/examples/react/prefetching) to our playground.

Proposed solution

Alternatives considered

No.

Do you want to create a pull request?

Yes

Query return extended observable directly

I saw that when you execute useQuery currently it returns an object with a result$ property.

Did you think about the possibility to return an observable directly that you extend with some other properties?

Like here

SSR snippets outdated?

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

No

Description

I couldn't understand how to piece together the SSR snipets.
it seems outdated.

Help?

if it helps here is my server.ts code.

import 'zone.js/dist/zone-node';

import { APP_BASE_HREF } from '@angular/common';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import * as compression from 'compression';
import { existsSync } from 'fs';
import { join } from 'path';

import bootstrap from './src/main.server';

// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  server.use(compression());
  const distFolder = join(process.cwd(), 'dist/apps/nx-ng-test-project/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html'))
    ? 'index.original.html'
    : 'index';

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/main/modules/express-engine)
  server.engine(
    'html',
    ngExpressEngine({
      bootstrap,
    })
  );

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get(
    '*.*',
    express.static(distFolder, {
      maxAge: '1y',
    })
  );

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, {
      req,
      providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }],
    });
  });

  return server;
}

function run(): void {
  const port = process.env['PORT'] || 4000;

  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = (mainModule && mainModule.filename) || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export default bootstrap;

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

./node_modules/xhr2/lib/xhr2.js:281
            throw new NetworkError(`Unsupported protocol ${this._url.protocol}`);
                  ^

Error
    at send (./node_modules/xhr2/lib/xhr2.js:281:19)
    at Observable._subscribe (/Users/omerprizner/dev/nx-projects/dist/apps/nx-ng-test-project/server/vendor.js:73345:13)
    at Observable._trySubscribe (/Users/omerprizner/dev/nx-projects/dist/apps/nx-ng-test-project/server/vendor.js:29130:19)
    at /Users/omerprizner/dev/nx-projects/dist/apps/nx-ng-test-project/server/vendor.js:29124:115
    at Object.errorContext (/Users/omerprizner/dev/nx-projects/dist/apps/nx-ng-test-project/server/vendor.js:38800:5)
    at Observable.subscribe (/Users/omerprizner/dev/nx-projects/dist/apps/nx-ng-test-project/server/vendor.js:29120:20)
    at /Users/omerprizner/dev/nx-projects/dist/apps/nx-ng-test-project/server/vendor.js:35662:57
    at OperatorSubscriber._this._next (/Users/omerprizner/dev/nx-projects/dist/apps/nx-ng-test-project/server/vendor.js:31916:9)
    at OperatorSubscriber.Subscriber.next (/Users/omerprizner/dev/nx-projects/dist/apps/nx-ng-test-project/server/vendor.js:29628:12)
    at /Users/omerprizner/dev/nx-projects/dist/apps/nx-ng-test-project/server/vendor.js:31255:20


### Please provide the environment you discovered this bug in

```true
NX + Angular universal

Anything else?

Help me <3

Do you want to create a pull request?

Yes

beforeEach with waitForAsync fails when trying to compile a component

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

No

Description

When trying to create a component and initially calling detectChanges as would be usually done:

beforeEach(waitForAsync(() => {
  TestBed.configureTestingModule({ declarations: [AppComponent] });
  TestBed.compileComponents();
  const component = TestBed.createComponent(AppComponent);
  component.detectChanges();
}));

All tests in the file will fail due to jest timeout.
It also doesn't matter if I attempt to detect changes outside of the beforeEach hook, because then only the first test will succeed, while all subsequent tests will fail.

Please provide a link to a minimal reproduction of the bug

https://github.com/cuddlecake/query/blob/main/packages/ng-query/src/lib/tests/component.spec.ts

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in

No response

Anything else?

My minimal reproduction is as minimal as it gets, but I first stumbled on this when I tried to introduce @ngneat/query in my app with a proper use case, involving an HTTP Request.

Do you want to create a pull request?

No

Support promise based queryFn function

Which @ngneat/query-* package(s) are relevant/releated to the feature request?

query

Description

I would like to use a basic async function as the queryFn.

For example this one:

export const getPets = async () => {
  const response = await fetch('https://pokeapi.co/api/v2/pokemon');
  const json: {
    results: { name: string; url: string }[];
  } = await response.json();

  return json;
};

Proposed solution

Add the extra types for all of the exported functions, so they will accept basic async functions where they can, instead of only supporting observables. Check if the queryFn returns a promise or observable. If it returns a promise, then use that/wrap it with from.

Alternatives considered

Wrapping every promise in from, but I would like cleaner code.

Do you want to create a pull request?

No

Github pages

Set up GitHub page for our playground.
Replace the local express app with a free online service for the API of the basic example with mutations.

ci.yml action is failing

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

No

Description

image

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in

No response

Anything else?

No response

Do you want to create a pull request?

Yes

The default configuration for `staleTime` will be removed if custom `QUERY_CLIENT_CONFIG` without `staleTime` property is provided

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

No

Description

Providing a custom QUERY_CLIENT_CONFIG as currently done in the playground app

return <QueryClientConfig>{
          defaultOptions: {
            queries: {
              queryFn,
            },
          },
        };

will overwrite/remove the default configuration of staleTime: Infinity in QueryClient:

export const QueryClient = new InjectionToken<QueryCore>('QueryClient', {
  providedIn: 'root',
  factory() {
    const options = inject(QUERY_CLIENT_OPTIONS);

    return new QueryCore({
      defaultOptions: {
        queries: {
          staleTime: Infinity,
          ...options?.defaultOptions?.queries,
        },
      },
      ...options,
    });
  },
});

The default configuration of staleTime should only be overwritten, if a custom configuration explicitly provide a staleTime.

Please provide a link to a minimal reproduction of the bug

#40

Please provide the exception or error you saw

`staleTime: Infinity` is not applied, hence the prefetching example https://github.com/ngneat/query/pull/40 does not work.

Please provide the environment you discovered this bug in

Discovered in https://github.com/ngneat/query/pull/40.

Anything else?

No response

Do you want to create a pull request?

Yes

refetchOnWindowFocus is not working

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

No

Description

When setting refetchOnWindowFocus: "always", I expect the query to refetch when I click outside, then inside the window. That is how it works for me in react. It doesn't work here for some reason.

import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { UseQuery } from '@ngneat/query';

@Component({
  selector: 'app-root',
  template: `<div>
    <div *ngIf="pokemon.result$ | async as pokemon">
      <p *ngIf="pokemon.isError">Error...</p>
      <div *ngIf="pokemon.data">
        <div *ngFor="let pokemon of pokemon.data.results">
          <div>{{ pokemon.name }}</div>
        </div>
      </div>
    </div>
  </div>`,
})
export class AppComponent {
  private useQuery = inject(UseQuery);
  private http = inject(HttpClient);
  getPokemon() {
    return this.useQuery(
      ['pokemon'],
      () => {
        return this.http.get<{
          results: { name: string; url: string }[];
        }>('https://pokeapi.co/api/v2/pokemon');
      },
      {
        refetchOnWindowFocus: 'always',
      }
    );
  }

  pokemon = this.getPokemon();
}

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in

No response

Anything else?

No response

Do you want to create a pull request?

No

`refetchOnWindowFocus` in module's providers doesn't have any effect

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

Yes

Description

In my module I have:

providers: [
    provideQueryClientOptions({
      defaultOptions: {
        queries: {
          refetchOnWindowFocus: false,
        },
      },
    }),
  ],

Then I call useQuery in a component, that declared in this module:

โ€ฆ
this.useQuery(
  ['todo', id],
  () => this.http.getTodo({ id })
).result$
โ€ฆ

After switching between tabs new requests are called.
However, if I add refetchOnWindowFocus to useQuery itself, it works fine:

โ€ฆ
this.useQuery(
  ['todo', id],
  () => this.http.getTodo({ id }),
  { refetchOnWindowFocus: false }
).result$
โ€ฆ

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in

Angular 15.1.3

Anything else?

No response

Do you want to create a pull request?

No

CI

Cypress

Array Utils

Which @ngneat/query-* package(s) are relevant/releated to the feature request?

No response

Description

Change addEntity to arrayPush and support flat array. Create arrayRemove, arrayUpdate, etc.

Proposed solution

Similiar API to https://opensource.salesforce.com/akita/docs/additional/array

Alternatives considered

None

Do you want to create a pull request?

No

Optimistic updates example doesn't work

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

Yes

Description

The optimistic updates example in the demo doesn't work.
Clicking the button doesn't do anything.

Please provide a link to a minimal reproduction of the bug

https://ngneat.github.io/query/optimistic-updates

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in

No response

Anything else?

No response

Do you want to create a pull request?

No

Query invalidation not working in some cases

Which @ngneat/query-* package(s) are the source of the bug?

query

Describe the bug

When creating and subscribing to the same query result multiple times (same key and query function) and unsubscribing one of the results (e.g. in a modal/dialog that gets destroyed after a while), it will cause a bug that prevents you from invalidating the query. If you try to invalidate (e.g. using invalidateQueries) the query, it will get stuck in "fetching" status forever.

Steps to reproduce

  • Create a query twice with same key and query function
  • Subscribe to both query results (Observer count in dev tools changes to 2)
  • Unsubscribe to second query (Observer count in dev tools changes to 1)
  • Try to invalidate query using query key via invalidateQueries
  • Dev Tools will show you that query is in 'fetching' state forever and will not succeed

Cause

I guess this is happening because of line 76 in base-query.ts:
(mergedOptions as any)['queryFn']?.[SUBSCRIPTION]?.unsubscribe();

Because the second query result gets unsubscribed it will unsubscribe sourceSubscription (utils.ts). Next time you try to invalidate, it will use the query function (queryFn$) to create new subscription and assigning it to the unsubscribed sourceSubscription. This will cause the originalQueryFn function to immediately get unsubscribed and the Promise that is returned will never resolve. Therefore the query is stuck forever.

Possible Solution

Maybe it would be enough to recreate the sourceSubscription every time the query function is executed.

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in

No response

Anything else?

No response

Do you want to create a pull request?

No

After an unsubscribe on result$ mutation, mutation is no longer working

Which @ngneat/query-* package(s) are the source of the bug?

query

Is this a regression?

No

Description

Hi
To reproduce create a mutation using the service, subscribe to the result$, unsubscribe to it, resubscribe --> all I receive is only a loading result.
My use case is I want to be able to create the mutation in a service and use it in multiple component as I want but after the first unsubscribe I am no longer able to use the mutation.
BR
Florent

Please provide a link to a minimal reproduction of the bug

#81

Please provide the exception or error you saw

After a unsubscribe to a result$ mutation the mutation is not longer working and stay in a loading state (as if the observable is no longer subscribe) even if a valid subscription is still on.

Please provide the environment you discovered this bug in

No response

Anything else?

No response

Do you want to create a pull request?

Yes

Refetch should return an observable

Think if we really need to support this method as we can use a higher-order observable instead.
If yes, the reset observer method should return an observable instead of a promise.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.