babel-types how to get Identifier value - babeljs

i want to replace Identifier with it's value, for example:
before:
import React from 'react';
const pkg = '#/src/index.tsx';
const Comp = React.lazy(() => import(pkg));
after:
import React from 'react';
const pkg = '#/src/index.tsx';
const Comp = React.lazy(() => import('#/src/index.tsx'));

Related

I work with github api on redux-toolkit(rtk-query) and have a problem

Uncaught Error: Warning: Middleware for RTK-Query API at reducerPath "github/api" has not been added to the store.
You must add the middleware for RTK-Query to function correctly!
import {configureStore} from "#reduxjs/toolkit";
import {githubApi} from "./github/github.api";
export const store = configureStore({
reducer: {
[githubApi.reducerPath]: githubApi.reducer
},
})
import {createApi, fetchBaseQuery} from "#reduxjs/toolkit/query/react";
export const githubApi = createApi({
reducerPath: 'github/api',
baseQuery: fetchBaseQuery({
baseUrl: 'https://api.github.com/'
}),
endpoints: build => ({
searchUsers: build.query<any, string>({
query: (search: string) => ({
url: `search/users`,
params: {
q: search
}
})
})
})
})
export const {useSearchUsersQuery} = githubApi
import React from "react";
import {useSearchUsersQuery} from "../store/github/github.api";
export function HomePage() {
const {isLoading, isError, data} = useSearchUsersQuery('anyname')
return (
<div>Home</div>
)
}
It's literally what it says - in your configureStore call, you skipped adding the RTK Query middleware.
export const store = configureStore({
reducer: {
[githubApi.reducerPath]: githubApi.reducer
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(githubApi.middleware),
})

reference error when I try to get a value from other slice redux toolkit?

I am trying to import a value form other slice that has some user information, any idea why I am getting this nasty error ? I read it is normal to request data from other slices, the error seem to be like the slice cannot find the store... below is my code structure, my store is at the top of my app, does this getState function works in a component only and not in slice to other slice .
import React from 'react';
import ReactDOM from 'react-dom';
import { HashRouter } from 'react-router-dom';
import App from './App';
import './index.css';
// Redux Tool Kit
import { store } from './app/store';
import { Provider } from 'react-redux';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
import {
RootState,
store
} from './store';
import {
createSlice,
PayloadAction
} from '#reduxjs/toolkit';
export interface miscState {
dayNumber: true,
dayOfWeek: false,
};
export const miscSlice = createSlice({
name: 'misc',
initialState,
reducers: {
setDisplayDay: (state, action: PayloadAction < {
bool: boolean;type: string
} > ) => {
const {
user,
uid
} = store.getState().global.currentUser;
const setDisplay = async() => {
const docRef = doc(db, colDynamic(user)[0], uid);
await updateDoc(docRef, {
[action.payload.type]: action.payload.bool,
});
};
},
},
});
// Values
export const MiscCurrentState = (state: RootState) => state.misc;
// Action creators are generated for each case reducer function
export const {
setDisplayDay
} = miscSlice.actions;
export default miscSlice.reducer;
import { configureStore } from '#reduxjs/toolkit';
// Global
import globalReducer from './globalSlice';
// Misc
import miscReducer from './miscSlice';
export const store = configureStore({
reducer: {
global: globalReducer,
misc: miscReducer,
},
});
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;
In Redux, you are not allowed to access the store from within a reducer. A reducer has to be a pure function that only reads the variables passed into it - so all information you have is the slice's own state and the action being dispatched. You are not allowed to read a global variable, have any kind of side effect or read from the global Redux store to get the data of another slice.

how to use selectors with a combineReducers when one of the child reducers relies on adapter?

students.reducer.ts
export const StudentsFeatureKey = 'students';
export interface StudentState {
studentProfile: fromStudProfReducer.StudentProfileState;
studentAdmin: fromStudAdminReducer.StudentAdminState;
}
export const reducer = combineReducers({
studentProfile: fromStudProfReducer.Reducer,
studentAdmin: fromStudAdminReducer.Reducer
});
student-profile.reducer.ts
export interface StudentProfileState extends EntityState<StudentProfileViewModel> {}
export const adapter = createEntityAdapter<StudentProfileViewModel>();
export const initialState: StudentProfileState = adapter.getInitialState();
export const Reducer = createReducer(
initialState
);
export const {
selectIds,
selectEntities,
selectAll,
selectTotal,
} = adapter.getSelectors();
student-profile.selectors.ts
export const getStudentsFeatureState =
createFeatureSelector<fromStudentsReducer.StudentState>(
fromStudentsReducer.StudentsFeatureKey
);
THIS SELECTOR IS FAILING --> TypeError: Cannot read property 'map' of undefined
export const selectAllStudentProfiles = createSelector(
getStudentsFeatureState,
fromStudProfReducer.selectAll,
(_, profiles) => profiles
);
student-facade.service.ts
private _testValue = this.store.pipe(
select(selectAllStudentProfiles),
tap(profiles => console.log('profiles: ', profiles))
).subscribe();
Thanks for helping
EDIT
selecting the parent feature slice is working just fine, i.e. when I use getStudentsFeatureState.
private _testValue = this.store.pipe(
select(getStudentsFeatureState),
tap(state => console.log('state: ', state))
).subscribe();
I'am getting the

Register is not a function when passing as a prop?

I use react-hook-form for the first time. I was reading the docs and followed along. Likewise, I already laid out my components and styled them. Now I am trying to alert the data out after the form submits.
This is the ContactForm
import React, { useState } from 'react';
import * as S from './style';
import { PrimaryButton } from '#element/Button';
import TextInput from '#element/TextInput';
import { useForm } from 'react-hook-form';
export const ContactForm = () => {
const { register, handleSubmit } = useForm();
const [firstName, setFirstName] = useState('');
const onSubmit = (data) => {
alert(JSON.stringify(data));
};
return (
<S.ContactFormWrapper onSubmit={handleSubmit(onSubmit)}>
<TextInput
name={'firstName'}
label={'First Name'}
state={firstName}
setState={setFirstName}
placeholder={'John'}
type={'text'}
width={'48%'}
options={{
maxLength: '20',
minLength: '2',
required: true,
}}
register={register}
/>
<PrimaryButton type={'submit'} text={'Send Message'} />
</S.ContactFormWrapper onSubmit={handleSubmit(onSubmit)}>
)
}
This is my Custom created TextInput
import React, { useEffect, useState } from 'react';
import * as S from './style';
const TextInput = ({
name,
label,
placeholder,
state,
setState,
type,
width,
register,
options,
}) => {
const [isActive, setIsActive] = useState(false);
return (
<S.TextInputWrapper inputWidth={width}>
<S.Label htmlFor={name} isActive={isActive}>
{label}
</S.Label>
<S.Input
placeholder={placeholder}
type={type}
name={name}
id={name}
{...register(name, options)}
onChange={(event) => setState(event.target.value)}
onFocus={() => setIsActive(true)}
onBlur={() => setIsActive(false)}
/>
</S.TextInputWrapper>
);
};
export default TextInput;
Error Message
TypeError: register is not a function {...register(name, options)}
I was searching on StackOverflow there was a Post, but the Answer was confusing for me and the Questioner Code was much different than mine. Because I think the error occurred because I use styled-components, and it is nested deep. I am confused because I was reading the docs and followed along.
If I spread the Error says, register is not a function else if I not spread it then the error is ... spread is required.
Hopefully you can bring light to my confusion.
Kind regards
Kuku
The simplest solution is to take advantage of react hook form's context and use the useFormContext hook.
Input Component
import { useFormContext } from "react-hook-form";
const TextInput = ({ name, options }) => {
const { register } = useFormContext();
return (
<S.Input
name={name}
{...register(name, options)}
/>
</S.TextInputWrapper>
);
};
Remove the input register function from the parent form
export const ContactForm = () => {
...other functions
return <TextInput name={'firstName'} options={{maxLength: '20' }} />;
}
An even simpler solution is to let react-hook-form control the form values and use the useController hook or Controller component.
import { useController } from "react-hook-form";
const TextInput = ({ name, options }) => {
const { field } = useController({ name, rules: options });
return <S.Input name={name} {...field} />
};
You can also get the input states using the useContoller hook to reduce the number of events your using.
import { useController } from "react-hook-form";
const TextInput = ({ name, options }) => {
const {
field,
fieldState: { error, invalid, isDirty, isTouched }
} = useController({ name, rules: options });
};
useFormContext is a good solution explained by #Sean W
Here is another solution without useFormContext, you can use register as usual instead of passing it as a prop. You just have to forward the ref of your TextInput.
👉🏻 You can find an instance here: https://stackoverflow.com/a/68667226/4973076

Unable to get value of service in #CanActivate decorator in component

I am using Angular 2.0.0-beta.15. I am trying to use #CanActivate in the component. Below is the piece of code.
#CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => {
console.log('loggedIn:' + isLoggedIn(next, previous));
console.log('isExists:' + isExists(next, previous))
})export class ParentLandingComponent {}
Now relevant piece of code in isExists.ts is as below:
import {Injector} from 'angular2/core';
import {appInjector} from './app-injector';
import {DataService} from '../services/data-services.service';
export const isExists = (next: ComponentInstruction, previous: ComponentInstruction) => {
let injector: Injector = appInjector();
let userService: UserService = injector.get(UserService);
let router: Router = injector.get(Router);
let cookieService: CookieService = injector.resolveAndInstantiate(CookieService);
dataService.isExists().subscribe(result => {
console.log('isExists:' + result);
if (result) {
console.log('result:' + result);
cookieService.removeAll();
router.navigate(['Login']);
return true;
} else {
return false;
}
});
};
I have added the following in boot.ts as well.
///<reference path="../../node_modules/angular2/typings/browser.d.ts"/>
import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS, ROUTER_DIRECTIVES, RouteConfig, Location, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {AppComponent} from './app.component';
import {HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/Rx';
import {DataService} from './services/data-services.service';
import {StateService} from './services/current-user-state.service';
import {appInjector} from './utils/app-injector';
import {HttpClient} from './services/http-client.service';
bootstrap(AppComponent, [DataService, StateService, HttpClient, ROUTER_PROVIDERS, HTTP_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy })])
.then(appRef => {
appInjector(appRef.injector);
});
When i running, I am getting value of isExists(next, previous) in #CanAnnotation as undefined instead of boolean value. Inside isExists.ts, I am getting correct value as result. But when i am passing boolean value based on value of result, I am getting undefined on annotation portion.Can anyone help me to know what could be the issue in this?
The lambda in CanActivate() annotation has to return boolean|Promise<boolean>. Based on your code it's not returning anything. I am guessing you will return the value from isExists(). But, also isExists() doesn't return anything that's why it's undefined. I see you are trying to return true/false from the subscribe method. But that return is asynchronous and will not be resolved as you intended.
I suggest you convert your Observable to Promise<boolean> and return it from isExists()
relevant part in isExists():
return dataService.isExists().map(result => { // change subscribe to 'map' in order to change the return type of the observable and do the other stuff
console.log('isExists:' + result);
if (result) {
console.log('result:' + result);
cookieService.removeAll();
router.navigate(['Login']);
return true;
} else {
return false;
}
}).toPromise();
#CanActivate():
#CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => {
console.log('loggedIn:' + isLoggedIn(next, previous));
return isExists(next, previous);
})
export class ParentLandingComponent {}