How to import i18next in React Native? - react-native

I'm trying to use react-i18next in a React Native app. When importing i18next at the top of my index.js or app.tsx file, the build crashes with this error:
ERROR TypeError: undefined is not a function, js engine: hermes
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes
Here is the code:
index.js:
import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";
import "i18n/index";
AppRegistry.registerComponent(appName, () => App);
i18/index.ts:
import i18n, { LanguageDetectorAsyncModule } from "i18next";
import { initReactI18next } from "react-i18next";
import { Platform, NativeModules } from "react-native";
import { AsyncStorage } from "react-native";
import en from "./en.json";
import fr from "./fr.json";
const languages = {
EN: "en",
FR: "fr",
};
const resources = {
en: { translation: en },
fr: { translation: fr },
};
const detectLocale = () => {
const storedLocale = AsyncStorage.getItem("locale");
if (storedLocale) {
return storedLocale;
}
const mobileLocale =
Platform.OS === "ios"
? NativeModules.SettingsManager.settings.AppleLocale ||
NativeModules.SettingsManager.settings.AppleLanguages[0]
: NativeModules.I18nManager.localeIdentifier;
if (mobileLocale) {
return mobileLocale;
}
return languages.EN;
};
const LanguageDetector = {
type: "languageDetector" as LanguageDetectorAsyncModule["type"],
async: false,
init: () => {},
detect: detectLocale,
cacheUserLanguage: () => {},
};
export default i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources,
fallbackLng: languages.EN,
keySeparator: ".",
whitelist: [languages.EN, languages.FR],
interpolation: { escapeValue: false },
});
How to fix this?

Try rerunning metro bundler and make sure there isn't another metro bundler running for another react native application.

Related

Exception: Property 'GraphQLError' doesn't exist

I'm trying to use GraphQL with Apollo and repack in my sample react native app. However, when I run the app in the simulator, I receive this error of GraphQLError not existing. If I comment out all the Apollo code in App.tsx, the app works just fine. Does anyone have any insight on if I'm using the webpack.configure.js incorrectly, or if I have an error in my code?
App.tsx
import { Federated } from '#callstack/repack/client';
import React from 'react';
import { ScrollView, Text, AppRegistry } from 'react-native';
import { ApolloProvider } from '#apollo/client';
import { ApolloClient, InMemoryCache, ApolloProvider } from '#apollo/client';
const App1 = React.lazy(() => Federated.importModule('app1', './App'));
// Initialize Apollo Client
const client = new ApolloClient({  uri: 'localhost:4000/graphql',  cache: new InMemoryCache()});
export default function App() {
return (
<ApolloProvider client={client}>
<ScrollView> <Text> Hello World</Text></ScrollView>
   <App1 />
</ApolloProvider>
);
}
webpack.config.js
rules: [{
test: /\.[jt]sx?$/,
include: [
/node_modules(.*[/\\])+react/,
/node_modules(.*[/\\])+#react-native/,
/node_modules(.*[/\\])+#react-native-community/,
/node_modules(.*[/\\])+#expo/,
/node_modules(.*[/\\])+pretty-format/,
/node_modules(.*[/\\])+metro/,
/node_modules(.*[/\\])+abort-controller/,
/node_modules(.*[/\\])+#callstack\/repack/,
/node_modules(.*[/\\])+#apollo\/client/,
/node_modules(.*[/\\])+graphql/,
/node_modules(.*[/\\])+core-js-pure/,
],
use: 'babel-loader',

How is it possible to make mocha work without having to use commonJS?

I am currently trying to learn how testing works and how to do it with mocha on react native.
This is a test from a tutorial I found:
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { Text } from 'react-native';
import { expect } from 'chai';
import App from './App';
Enzyme.configure({ adapter: new Adapter() });
describe('<App>', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<App />);
});
it('renders default Text', () => {
expect(wrapper.find(Text)).to.have.lengthOf(3);
});
});
My problem is that whenever I run the test I get his back:
import React from 'react';
^^^^^^
SyntaxError: Cannot use import statement outside a module
When I change the import statements to require, I then get this error:
wrapper = shallow(<App />);
^
SyntaxError: Unexpected token '<'
I don't really understand how I can make mocha work on react native... or could someone recommend some resources please?

How to solve "Unable to resolve module" issue with react-redux?

I'm building a react-native app with Expo, when I doing refactor job and suddenly I can't open my app with Expo client, it shows an error
TypeError: (0, _redux.combinReducers) is not a function. (In '(0, _redux.combineReducers)(reducers)', '(0, _redux.combineReducers)' is undefined)
after some researching I see some reason cause this issue is cause the same folder name with redux, which I made this mistake also, so I change the folder name to "appRedux", after that the error message change to
Unable to resolve "../../../../src/redux" from "node_modules\react-redux\lib\connect\mapDispatchToProps.js"
I'm sure I've wrapped my App component in Provider as this solution said, but just no luck to solve it.
I've been stuck in here for few days, please help me to solve this issue, if need more info please let me know, any suggestion is appreciated.
App.js
import React, { Component } from 'react';
import Navigation from './src/navigation'
import { Provider } from 'react-redux'
import { getStore, getPersistor } from './src/store/configureStore'
import { PersistGate } from 'redux-persist/integration/react'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import { ApolloProvider } from '#apollo/react-hooks'
import { getClient } from './src/services/GraphQL/Client'
const store = getStore()
const persistor = getPersistor()
const client = getClient()
export default class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<Provider store={store} >
<PersistGate persistor={persistor}>
<SafeAreaProvider>
<Navigation />
</SafeAreaProvider>
</PersistGate>
</Provider>
</ApolloProvider>
);
}
}
configureStore.js
import { createStore, applyMiddleware } from 'redux'
import { persistStore } from 'redux-persist'
import reducers from '#redux'
import thunk from 'redux-thunk'
const store = createStore(reducers, applyMiddleware(thunk))
const persistor = persistStore(store)
const getPersistor = () => persistor
const getStore = () => store
export {
getStore,
getPersistor
}
Reducers.js
import { combineReducers } from 'redux'
import { persistCombineReducers, persistReducer } from 'redux-persist'
import { AsyncStorage } from 'react-native'
import carts from './carts'
import app from './app'
import user from './user'
const rootConfig = {
key: 'root',
storage: AsyncStorage,
blacklist: [
'app',
'carts',
'user'
]
}
const appConfig = {
key: 'app',
storage: AsyncStorage,
blacklist: [
'selectedDate',
'selectedDateIndex',
'isFetching',
'showFilter'
]
}
const cartConfig = {
key: 'carts',
storage: AsyncStorage,
blacklist: [
'isFetching',
'error'
]
}
const userConfig = {
key: 'user',
storage: AsyncStorage,
blacklist: [
'isFetching',
'error',
'history'
]
}
export default persistCombineReducers(rootConfig, {
app: persistReducer(appConfig, app),
carts: persistReducer(cartConfig, carts),
user: persistReducer(userConfig, user)
})
Finally I solve this issue by start expo client with
expo start -c
which will start expo app with clearing the cache, hope this will help someone facing the same issue

Exception in HostFunction: <unknown> when trying to push new screen

Issue Description
Trying to push a new screen with
Navigation.push(this, {
component: {
name: 'awesome-places.AuthScreen' }})
And getting an error Exepction in HostFunction <unknown>
Error Screenshot
Steps to Reproduce / Code Snippets / Screenshots
Create RN app, install required modules (redux, react-redux, react-native-navigation, react-vector-icons) and run code on Android device.
Add relevant code, App.js and component that causes the error. I tried running Navigation.push with this.props.componentId but when I press the button there is no response
App.js
import { Navigation } from 'react-native-navigation';
import { Provider } from 'react-redux';
import AuthScreen from './src/screens/Auth/Auth';
import SharePlaceScreen from './src/screens/SharePlace/SharePlace';
import FindPlaceScreen from './src/screens/FindPlace/FindPlace';
import PlaceDetailScreen from './src/screens/PlaceDetail/PlaceDetail';
import configureStore from './src/store/configureStore';
const store = configureStore();
// Register Screens
Navigation.registerComponentWithRedux("awesome-places.AuthScreen", () => AuthScreen, Provider, store);
Navigation.registerComponentWithRedux("awesome-places.SharePlaceScreen", () => SharePlaceScreen, Provider, store);
Navigation.registerComponentWithRedux("awesome-places.FindPlaceScreen", () => FindPlaceScreen, Provider, store);
Navigation.registerComponent("awesome-places.PlaceDetailScreen", () => PlaceDetailScreen);
// Start an App
Navigation.events().registerAppLaunchedListener(() => {
Navigation.setRoot({
root: {
component: {
name: 'awesome-places.AuthScreen'
}
}
});
});
FindPlace.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { connect } from 'react-redux';
import { Navigation } from 'react-native-navigation';
import PlaceList from '../../components/PlaceList/PlaceList';
class FindPlaceScreen extends Component {
Navigation.push(this, {
component: {
name: 'awesome-places.AuthScreen',
}
})
}
render () {
return(
<View>
<PlaceList places={this.props.places} onItemSelected={this.itemSelectedHandler} />
</View>
);
}
}
const mapStateToProps = state => {
return {
places: state.places.places
}
}
export default connect(mapStateToProps)(FindPlaceScreen);
Environment
React Native Navigation version: 2.17.0
React Native version: 0.59.4
Platform(s) (iOS, Android, or both?): Android
Device info (Simulator/Device? OS version? Debug/Release?): Android 7.1.2, Debug
I noticed you're pushing the screen with this instead of an explicit componentId.
When calling Navigation.push, the first argument needs to be a componentId. See the docs for reference.
Also, this might not be a problem, but registerComponentWithRedux is deprecated and you should register the screen with the new api

undefined is not a function (evaluating 'decorator(target, property, desc)')

I want to integrate mobx and mobx-persist with react-navigation.
I read these articles:
[1] https://hackernoon.com/react-navigation-with-mobx-2064fcdaa25b
[2] https://blog.callstack.io/write-react-native-apps-in-2017-style-with-mobx-e2dffc209fcb
[3] https://github.com/react-navigation/react-navigation/blob/8e8d3d562c9e80616f145f97ffb02dcf2048e67e/docs/guides/Mobx-Integration.md
[4] MobX + React Native : way to inject stores
[5] MobX - Why should I use `observer` when I could use `inject` when injecting data into a React component
[6] Injecting Store in React component results in Error
But I still got this error:
undefined is not a function (evaluating 'decorator(target, property, desc)')
This is my App.js render:
render() {
const hydrate = create({
storage: AsyncStorage
});
hydrate('playerStore', stores.PlayerStore);
hydrate('settingStore', stores.SettingStore);
// .then(
// // () => console.warn('some hydrated')
// );
return <Provider {...stores} >
<AppWithNavigationState />
</Provider>;
}
This is my routeStore.js:
import {observable} from "mobx";
import {action} from "mobx-react/native";
import AppDrawer from "../appDrawer";
import {autobind} from 'core-decorators';
export default class RouteStore {
#observable.ref navigationState = {
index: 0,
routes: [
{ key: "R1", routeName: "ContentStack" },
],
};
#action
dispatchNavigation(action, stackState = true) {
const previousNavState = stackState ? this.navigationState : null;
return this.navigationState = AppDrawer.router.getStateForAction(action, previousNavState);
}
}
This is my appWithNavigationState.js:
import React from 'react';
import {observer, inject} from "mobx-react/native";
import {addNavigationHelpers} from "react-navigation";
import AppDrawer from "../appDrawer";
#inject(stores => ({ routeStore: stores.RouteStore }))
#observer
export default class AppWithNavigationState extends React.Component {
render() {
return (
<AppDrawer navigation={addNavigationHelpers({
dispatch: this.props.routeStore.dispatchNavigation,
state: this.props.routeStore.navigationState,
})} />
);
}
}
I also use decorator package as below:
npm install babel-plugin-transform-decorators-legacy --save-dev
and this setting in babelrc file:
{
"presets": ["react-native"],
"plugins": ["transform-decorators-legacy"]
}
Can you help me to fix this?
By default, the React Native Babel transform configuration does not include support for ES7 decorators.
You can add them by first installing the decorator package:
npm install babel-plugin-transform-decorators-legacy --save-dev
And then adding the plugin in your .babelrc file in the project root:
{
"presets": ["react-native"],
"plugins": ["transform-decorators-legacy"]
}