I'm supposed to generate an API call from a random API site with NgRx, the browser should be showing an input, in which as I write something it should pop up a word or multiple words from the API according to the letters I've written.
I have just started experimenting with NgRx and whilst I'm starting to understand the general flow, I'm having a hard time building up a working code for this task. Can you please help me?
Inside the app folder of ngrx I have created a "call" folder which contains call.actions.ts, call.reducer.ts, call.selector.ts, call.state.ts
Here's what I've written so far:
src/app/call/call.state.ts
export interface ICall {
readonly query: string;
}
src/app/call/call.actions.ts
import { createAction, props } from '@ngrx/store';
import { ICall } from './call.state';
export const searchQueryChanged = createAction(
'[Wherever] Search query changed',
props<{ query: string }>()
);
src/app/call/call.reducer.ts
import { createReducer, on, Action } from '@ngrx/store';
import { ICall } from './call.state';
import { searchQueryChanged } from './call.actions';
export const initialState: ICall = {
query: '',
};
createReducer(
initialState,
on(searchQueryChanged, (state, { query }) => ({
...state,
query,
}))
);
src/app/app.component.html
<input
[value]="query$ | async"
(input)="queryTextChanged($event.target.value)"
/>
src/app/app.component.ts
import { Component } from '@angular/core';
import { searchQueryChanged } from './call/call.actions';
import { getQuery } from './call/call.selectors';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'ngrx-ex-api';
}
class SearchThingComponent {
readonly query$ = this.store.select(getQuery);
queryTextChanged(query: string) {
this.store.dispatch(searchQueryChanged({ query });
}
}
class SearchThingComponent {
suggestions$ = this.query$.pipe(
switchMap(query => doTheThing)
);
query$: any;
}
src/app/call.selectors.ts
import { createSelector, createFeatureSelector } from '@ngrx/store';
import { ICall } from './call.state';
export const whateverFeatureSelector = createFeatureSelector<ICall>('call');
export const getQuery = createSelector(
whateverFeatureSelector,
(state) => state.query
);
Currently both app.component.html and app.component.ts present errors which I don't really know how to solve. If you have in mind another way to address the problem please tell me, thank you.