this is my app.js code
im working 2 days on this js > i want to add custom font to my expo project but i cant .
i read expo document but i cant add custom font
can anybody change my code with custom font and tell me where to need change ?
( i create /assest/font directore with my font name : sasanisasi.ttf )
thanks
import React, { useEffect } from "react";
import {
YellowBox,
View,
Platform,
Dimensions,
KeyboardAvoidingView,
} from "react-native";
YellowBox.ignoreWarnings([
"Warning: componentWillMount is deprecated",
"Warning: componentWillReceiveProps is deprecated",
"Remote debugger is in a background tab which",
"Debugger and device times have drifted",
"Warning: isMounted(...) is deprecated",
"Setting a timer",
"<InputAccessoryView> is not supported on Android yet.",
"Class EX",
"Require cycle:",
]);
console.disableYellowBox = true;
import { AppLoading } from "expo";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/lib/integration/react";
import { store, persistor } from "./configureStore";
import configureApp from "./configureApp.json";
import RootStack from "./app/routes";
import axios from "axios";
import { updateFocus } from "./app/wiloke-elements";
import Constants from "expo-constants";
import { Asset } from "expo-asset";
import { screenHeight } from "./app/constants/styleConstants";
axios.defaults.baseURL = `${configureApp.api.baseUrl.replace(
/\/$/g,
""
)}/wp-json/wiloke/v3`;
axios.defaults.timeout = configureApp.api.timeout;
// axios.defaults.headers["Cache-Control"] = "no-cache";
const deviceHeight = Dimensions.get("screen").height;
const navigationBarHeight =
deviceHeight - screenHeight - Constants.statusBarHeight;
const AndroidHeight =
navigationBarHeight > 20
? deviceHeight - Constants.statusBarHeight
: screenHeight - Constants.statusBarHeight;
const android = Platform.OS === "android";
const App = () => {
const _cacheResourcesAsync = async () => {
const images = [
require("./assets/loginCover.png"),
require("./assets/logo.png"),
];
const cacheImages = images.map((image) => {
return Asset.fromModule(image).downloadAsync();
});
return Promise.all(cacheImages);
};
useEffect(() => {
_cacheResourcesAsync();
}, []);
return (
<PersistGate loading={null} persistor={persistor}>
<Provider store={store}>
<RootStack />
</Provider>
</PersistGate>
);
};
export default App;
// if (__DEV__) {
// // #ts-ignore
// global.XMLHttpRequest = global.originalXMLHttpRequest ? global.originalXMLHttpRequest : global.XMLHttpRequest;
// // #ts-ignore
// global.FormData = global.originalFormData ? global.originalFormData : global.FormData;
// // eslint-disable-next-line #typescript-eslint/no-unused-expressions
// fetch; // Ensure to get the lazy property
// // #ts-ignore
// if (window.__FETCH_SUPPORT__) {
// // it's RNDebugger only to have
// // #ts-ignore
// window.__FETCH_SUPPORT__.blob = false;
// } else {
// /*
// * Set __FETCH_SUPPORT__ to false is just work for `fetch`.
// * If you're using another way you can just use the native Blob and remove the `else` statement
// */
// // #ts-ignore
// global.Blob = global.originalBlob ? global.originalBlob : global.Blob;
// // #ts-ignore
// global.FileReader = global.originalFileReader ? global.originalFileReader : global.FileReader;
// }
// }
Did you try the following:
// Your imports
import * as Font from 'expo-font';
// Your code
let customFonts = {
'Sasanisasi': require('./assets/font/sasanisasi.ttf'), // relative path
};
async _loadFontsAsync() {
await Font.loadAsync(customFonts);
}
useEffect(() => {
_cacheResourcesAsync();
_loadFontsAsync()
}, []);
// Remaining code
It's from expo documentation.
Related
using nestjs framework and with a repository class that uses mongoose to do the CRUD operations we have a simple users.repository.ts file like this:
#Injectable()
export class UserRepository {
constructor(#InjectModel(User.name) private userModel: Model<UserDocument>) {}
async create(createUserInput: CreateUserInput) {
const createdUser = new this.userModel(createUserInput);
return await createdUser.save();
}
}
async findById(_id: MongooseSchema.Types.ObjectId) {
return await this.userModel.findById(_id).exec();
}
and it works normally when the server is up.
consider this users.repository.spec file :
import { Test, TestingModule } from '#nestjs/testing';
import { getModelToken } from '#nestjs/mongoose';
import { Model } from 'mongoose';
// User is my class and UserDocument is my typescript type
// ie. export type UserDocument = User & Document; <-- Mongoose Type
import { User, UserDocument } from '../domain/user.model';
import { UserRepository } from './users.repository';
//import graphqlScalars from 'graphql-scalar-types';
describe('UsersRepository', () => {
let mockUserModel: Model<UserDocument>;
let mockRepository: UserRepository;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: getModelToken(User.name),
useValue: Model, // <-- Use the Model Class from Mongoose
},
UserRepository,
//graphqlScalars,
],
}).compile();
// Make sure to use the correct Document Type for the 'module.get' func
mockUserModel = module.get<Model<UserDocument>>(getModelToken(User.name));
mockRepository = module.get<UserRepository>(UserRepository);
});
it('should be defined', () => {
expect(mockRepository).toBeDefined();
});
it('should return a user doc', async () => {
// arrange
const user = new User();
const userId = user._id;
const spy = jest
.spyOn(mockUserModel, 'findById') // <- spy
.mockResolvedValue(user as UserDocument); // <- set resolved value
// act
await mockRepository.findById(userId);
// assert
expect(spy).toBeCalled();
});
});
so my question:
for the should return a user doc test i get TypeError: metatype is not a constructor when and i guess
.mockResolvedValue(user as UserDocument);
should be fixed.
Note:graphql is used the query to the API and i have no idea that if the scalars should be provieded or not, if i uncomment the scalar, the expect(mockRepository).toBeDefined(); test would not pass any more
so any idea to fix the test would be apreciated.
to handle a chained .exec we should define it via mockReturnThis():
static findById = jest.fn().mockReturnThis();
I needed the constructor to be called via new so i preferd to define a mock class in this way:
class UserModelMock {
constructor(private data) {}
new = jest.fn().mockResolvedValue(this.data);
save = jest.fn().mockResolvedValue(this.data);
static find = jest.fn().mockResolvedValue(mockUser());
static create = jest.fn().mockResolvedValue(mockUser());
static remove = jest.fn().mockResolvedValueOnce(true);
static exists = jest.fn().mockResolvedValue(false);
static findOne = jest.fn().mockResolvedValue(mockUser());
static findByIdAndUpdate = jest.fn().mockResolvedValue(mockUser());
static findByIdAndDelete = jest.fn().mockReturnThis();
static exec = jest.fn();
static deleteOne = jest.fn().mockResolvedValue(true);
static findById = jest.fn().mockReturnThis();
}
Having a hard time understanding this newest expo bottom tabs
I dont see an initital params on the node_module for the bottomtabs or any params property... has anyone done this? essentially we have component for two bottom tabs and a different effect depending on that tab.
So 1. Can we pass Params into bottomTabs? 2. if so how?
error we get with TS is:
The expected type comes from property 'initialParams' which is declared here on type 'IntrinsicAttributes & RouteConfig<RootTabParamList, "TabThree", TabNavigationState, BottomTabNavigationOptions, BottomTabNavigationEventMap>'
<BottomTab.Screen
name="Episodes"
component={EpisodesScreen}
initialParams={{
type: "episodes",
}}
options={{
title: 'Episodes',
tabBarIcon: ({ color }) => <TabBarFeatherIcon name="headphones" color={color} />,
}}
/>
<BottomTab.Screen
name="TabThree"
component={EpisodesScreen}
initialParams={{
type: "quickGuides",
displayType: "grid",
}}
from the node_module::
import {
createNavigatorFactory,
DefaultNavigatorOptions,
ParamListBase,
TabActionHelpers,
TabNavigationState,
TabRouter,
TabRouterOptions,
useNavigationBuilder,
} from '#react-navigation/native';
import * as React from 'react';
import warnOnce from 'warn-once';
import type {
BottomTabNavigationConfig,
BottomTabNavigationEventMap,
BottomTabNavigationOptions,
} from '../types';
import BottomTabView from '../views/BottomTabView';
type Props = DefaultNavigatorOptions<
ParamListBase,
TabNavigationState<ParamListBase>,
BottomTabNavigationOptions,
BottomTabNavigationEventMap
> &
TabRouterOptions &
BottomTabNavigationConfig;
function BottomTabNavigator({
initialRouteName,
backBehavior,
children,
screenListeners,
screenOptions,
sceneContainerStyle,
...restWithDeprecated
}: Props) {
const {
// #ts-expect-error: lazy is deprecated
lazy,
// #ts-expect-error: tabBarOptions is deprecated
tabBarOptions,
...rest
} = restWithDeprecated;
let defaultScreenOptions: BottomTabNavigationOptions = {};
if (tabBarOptions) {
Object.assign(defaultScreenOptions, {
tabBarHideOnKeyboard: tabBarOptions.keyboardHidesTabBar,
tabBarActiveTintColor: tabBarOptions.activeTintColor,
tabBarInactiveTintColor: tabBarOptions.inactiveTintColor,
tabBarActiveBackgroundColor: tabBarOptions.activeBackgroundColor,
tabBarInactiveBackgroundColor: tabBarOptions.inactiveBackgroundColor,
tabBarAllowFontScaling: tabBarOptions.allowFontScaling,
tabBarShowLabel: tabBarOptions.showLabel,
tabBarLabelStyle: tabBarOptions.labelStyle,
tabBarIconStyle: tabBarOptions.iconStyle,
tabBarItemStyle: tabBarOptions.tabStyle,
tabBarLabelPosition:
tabBarOptions.labelPosition ??
(tabBarOptions.adaptive === false ? 'below-icon' : undefined),
tabBarStyle: [
{ display: tabBarOptions.tabBarVisible ? 'none' : 'flex' },
defaultScreenOptions.tabBarStyle,
],
});
(
Object.keys(defaultScreenOptions) as (keyof BottomTabNavigationOptions)[]
).forEach((key) => {
if (defaultScreenOptions[key] === undefined) {
// eslint-disable-next-line #typescript-eslint/no-dynamic-delete
delete defaultScreenOptions[key];
}
});
warnOnce(
tabBarOptions,
`Bottom Tab Navigator: 'tabBarOptions' is deprecated. Migrate the options to
'screenOptions' instead.\n\nPlace the following in 'screenOptions' in your code to keep
current behavior:\n\n${JSON.stringify(
defaultScreenOptions,
null,
2
)}\n\nSee https://reactnavigation.org/docs/bottom-tab-navigator#options for more
details.`
);
}
if (typeof lazy === 'boolean') {
defaultScreenOptions.lazy = lazy;
warnOnce(
true,
`Bottom Tab Navigator: 'lazy' in props is deprecated. Move it to 'screenOptions'
instead.\n\nSee https://reactnavigation.org/docs/bottom-tab-navigator/#lazy for more
details.`
);
}
const { state, descriptors, navigation, NavigationContent } =
useNavigationBuilder<
TabNavigationState<ParamListBase>,
TabRouterOptions,
TabActionHelpers<ParamListBase>,
BottomTabNavigationOptions,
BottomTabNavigationEventMap
>(TabRouter, {
initialRouteName,
backBehavior,
children,
screenListeners,
screenOptions,
defaultScreenOptions,
});
return (
<NavigationContent>
<BottomTabView
{...rest}
state={state}
navigation={navigation}
descriptors={descriptors}
sceneContainerStyle={sceneContainerStyle}
/>
</NavigationContent>
);
}
export default createNavigatorFactory<
TabNavigationState<ParamListBase>,
BottomTabNavigationOptions,
BottomTabNavigationEventMap,
typeof BottomTabNavigator
>(BottomTabNavigator);
only way i found to get my componenet to render on two different routes from the bottom tabs is to use the useNavigationState
import { useNavigationState } from "#react-navigation/native"
made a constant to check the route name and then on use effect we check the case...
const screenName = useNavigationState((state) =>
state.routes[state.index].name)
const type = screenName
useEffect(() => {
switch (type) {
case "Episodes":
setTitle("Episodes")
setIsLoading(false)
break
case "quickGuides":
setTitle("Quick Guides")
setIsLoading(false)
break
}
}, [])
I'm practicing test-first development and I want to ensure that method in a class always calls my logger at the warn level with a message. My class is defined like so:
import { log4js } from '../config/log4js-config'
export const logger = log4js.getLogger('myClass')
class MyClass {
sum(numbers) {
const reducer = (accumulator, currentValue) => accumulator + currentValue
const retval = numbers.reduce(reducer))
if (retval < 0) {
logger.warn('The sum is less than zero!')
}
return retval
}
}
const myClass = new MyClass()
export { myClass }
My test looks like this:
import { myClass, logger } from './MyClass'
import { log4js } from '../config/log4js-config'
jest.mock('log4js')
describe('MyClass', () => {
it('logs a warn-level message if sum is negative', () => {
logger.warn = jest.fn()
logger._log = jest.fn()
myClass.sum([0, -1])
expect(logger.warn).toHaveBeenCalled() // <--- fails
expect(logger._log).toHaveBeenCalled() // <--- fails
})
})
I've also tried to mock log4js.Logger._log in the setup but that didn't seem to work either. 😕 Any suggestions are appreciated!
The thing with mocking is that you need to provide the mock, simplest method for me is through the mock factory. However i would recomend also some refactoring:
import { getLogger } from 'log4js'
export const logger = getLogger('myClass')
logger.level = 'debug'
// export the class itself to avoid memory leaks
export class MyClass {
// would consider even export just the sum function
sum(numbers) {
const reducer = (accumulator, currentValue) => accumulator + currentValue
const retval = numbers.reduce(reducer))
if (retval < 0) {
logger.warn('The sum is less than zero!')
}
return retval
}
}
import log4js from 'log4js';
import { MyClass } from "./class";
jest.mock('log4js', () => {
// using the mock factory we mimic the library.
// this mock function is outside the mockImplementation
// because we want to check the same mock in every test,
// not create a new one mock every log4js.getLogger()
const warn = jest.fn()
return {
getLogger: jest.fn().mockImplementation(() => ({
level: jest.fn(),
warn,
})),
}
})
beforeEach(() => {
// reset modules to avoid leaky scenarios
jest.resetModules()
})
// this is just some good habits, if we rename the module
describe(MyClass, () => {
it('logs a warn-level message if sum is negative', () => {
const myClass = new MyClass()
myClass.sum([0, -1])
// now we can check the mocks
expect(log4js.getLogger).toHaveBeenCalledTimes(1) // <--- passes
// check exactly the number of calls to be extra sure
expect(log4js.getLogger().warn).toHaveBeenCalledTimes(1) // <--- passes
})
})
Maybe simply spying on logger methods can do the trick
import { myClass, logger } from './MyClass'
describe('MyClass', () => {
it('logs a warn-level message if sum is negative', () => {
const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => {});
const _logSpy = jest.spyOn(logger, '_log').mockImplementation(() => {});
myClass.sum([0, -1])
expect(warnSpy).toHaveBeenCalled()
expect(_logSpy).toHaveBeenCalled()
})
})
I'm attempting to add objects into my Redux store during a unit test to ensure my reducers and actions are working properly. It looks like the state that is showing up is the INITIAL_STATE from the reducer file. However, any time I add a new item into the reducer state, nothing happens. I'm presuming it's because it's adding too slow and it's async. Not really sure how to approach this.
Reducer/Action Test
/***********************
TESTING THE REDUX STORE
***********************/
describe('>>>Redux Store for Budget Functionality', () => {
beforeEach(() => {
store = configureStore();
})
it('Should successfully add a new budget into the store', () => {
let budgetCategory = testHelper.testBudgetCategory;
//Will auto dispatch since we are using redux-actions
const action = addBudgetCategoryRequest(budgetCategory);
const actual = store.getState().getIn(['budget', 'budgetCategories']).toJS()
const expected = [testHelper.testBudgetCategory];
expect(actual).toEqual(expected);
})
Store File
import {createStore, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducers';
export function configureStore(){
// Use redux dev tools if available, otherwise use default composition;
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducers, composeEnhancers(
applyMiddleware(thunk)
));
return store;
}
My entire reducer/action create file
import Immutable from 'immutable'
import { createAction } from 'redux-actions';
import axios from 'axios';
import moment from 'moment';
/**************
INITIAL STATE
***************/
export const INITIAL_STATE = Immutable.fromJS({
budgetCategories: [],
budgetFormEditable: {errors: [{budgetNameError: false, monthlyCostError: false}] },
});
/**************
TYPES
***************/
export const ADD_BUDGET = 'src/Budget/ADD_BUDGET';
export const ADD_EDITABLE_FIELD_ERRORS = 'src/Budget/ADD_EDITABLE_FIELD_ERRORS';
export const UPDATE_BUDGET_ENTRY = 'src/Budget/UPDATE_BUDGET_ENTRY';
/**************
REDUCER LOGIC FLOW
***************/
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case ADD_BUDGET:
return state.updateIn(['budgetCategories'], arr => arr.push(Immutable.fromJS(action.payload)))
case ADD_EDITABLE_FIELD_ERRORS:
return state.setIn(['budgetFormEditable', 'errors', 0], Immutable.fromJS(action.payload))
case UPDATE_BUDGET_ENTRY:
console.log("The field that we are editing is " + action.payload.editedStateIndex);
return state.setIn(
[
'budgetCategories',
action.payload.editedStateIndex,
], Immutable.fromJS(action.payload.newBudget));
default:
return state;
}
}
/**************
ACTIONS CREATORS
***************/
export const addBudget = createAction(ADD_BUDGET);
export const addEditableFieldErrors = createAction(ADD_EDITABLE_FIELD_ERRORS);
export const updateBudgetEntry = createAction(UPDATE_BUDGET_ENTRY);
/**************
ACTION REQUESTS
***************/
//TODO: Honestly, this is pretty unnecessary as I am not resolving promises
export function addBudgetCategoryRequest(data) {
return (dispatch) => {
dispatch(addBudget(data));
}
}
How to evade this error: VM18193:27 Unable to open database ReferenceError: sqlitePlugin is not defined(…)
setTimeout(function() {
let db = new SQLite();
db.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
db.executeSql("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT)", {}).then((data) => {
console.log("TABLE CREATED: ", data);
}, (error) => {
console.error("Unable to execute sql", error);
})
}, (error) => {
console.error("Unable to open database", error);
});
}, 2000);
How can i execute some query?
if(SqlSettingsService.openDb){
this.db = SqlSettingsService.getDB();
this.db.executeSql("CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT", {}).then
instead i get error.
console:
SqlSettingsService() starts
VM21750:27 Unhandled Promise rejection: Cannot read property 'executeSql' of null ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'executeSql' of null(…) TypeError: Cannot read property 'executeSql' of null
The plugin sqlLite does not work in a browser, you can use Websql for the browser instead (with compatible browsers, including Chrome and Opera as far as I know).
Transactions written for Websql are compatible with transactions written for SQLite.
Here is a service I have done to manage the Connection to the DB and make it work regardless if the program runs in a browser or a on real device:
import { Injectable } from '#angular/core';
import { SQLite } from 'ionic-native';
import { Platform } from 'ionic-angular';
import { Storage } from '#ionic/storage';
#Injectable()
export class SqlSettingsService {
private db: any = null;
private isOpened: boolean = false;
constructor() {
console.log('SqlSettingsService() starts');
}
public getDB(){
return this.db;
}
public openDb = (platform:Platform,winSer:any):Promise<any> => {
console.log('SqlSettingsService() opend DB starts');
let p:Promise<any>;
if(!this.isOpened){
this.isOpened = true;
if(platform.is('core')){
this.db = winSer.window.openDatabase("ionic2BrowserDev","1.0","",5*1024*1024);
p = new Promise(function(resolve,reject){resolve('websql success')});
} else {
this.db = new SQLite();
p = this.db.openDatabase({
name: 'data.db',
location: 'default' // the location field is required
}).then(
()=>{console.log("SqlSettingsService open db successful")},
(err)=>{console.error(err)}
);
}
} else {
p = new Promise(function(resolve,reject){
resolve('db already opened');
});
}
return p;
}
public closeDb = () => {
this.isOpened = false;
return this.db.close();
}
}
winSer is another service to access the window Object that I use in my app.component.ts when I call openDB() on SqlSettingsService. It's just this:
import { Injectable } from '#angular/core';
#Injectable()
export class WindowService {
public window = window;
}
To execute query:
[SqlSettingsService-instance].openDb();
[SqlSettingsSevice-instance].getDB().transaction(
function(tx){
tx.executeSql([your sql],[bracket values you want to pass],success,error);
function success(tx,rs){
console.log("success exec sql: ")
console.info(rs);
}
function error(tx,error){
console.log('execSqlCustom error ' + error.message + " for tx " + tx);
}
});