Access mobx stores from any component in react-native - javascript

I'm new to react-native and react world, I'm using mobx store for state management as a single source of truth, I want to be able to access globalStore object from ANY component in my application without having to import globalStore, I think this MIGHT be possible with react Context-Provider API but I'm still a newbie.
My globalStore (I access all stores from this root store):
import { PostStore } from '../stores/PostStore.js'
import { VenueStore } from '../stores/VenueStore.js'
class GlobalStore
{
postStore;
venueStore;
constructor()
{
this.postStore = new PostStore(this);
this.venueStore = new VenueStore(this);
}
}
export default new GlobalStore;
In my functional components I want to be able to to something simple like:
onPress={ globalStore.userStore.loggedUser }
without having to import globalStore into my components
My App.js component:
import React, { useEffect } from 'react'
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import ROOTSTACK1 from '#components/navigators/ROOTSTACK1';
import { SafeAreaView, AsyncStorage } from "react-native";
import global from '#styles/Global';
const Stack = createStackNavigator();
function App()
{
return (
<SafeAreaView style={[ global.androidSafeArea ]}>
<NavigationContainer>
<ROOTSTACK1></ROOTSTACK1>
</NavigationContainer>
</SafeAreaView>
);
}
export default App;

Related

How to use Redux state in _app.tsx (NextJS)

This is the code to my _app.tsx
import '../styles/globals.css'
import AppNav from '../components/AppNav'
import type { AppProps } from 'next/app'
import { store } from '../store'
import { Provider } from 'react-redux'
import { useSelector, useDispatch } from 'react-redux'
import { RootState } from '../store'
function MyApp({ Component, pageProps }: AppProps) {
const user = useSelector((state: RootState) => state.user.value)
return (
<Provider store={store}>
<div className='global_container'>
<AppNav />
<Component {...pageProps} />
</div>
</Provider>
)
}
export default MyApp
In the code, I am trying to use the user redux state inside _app.tsx, but it gives me an error: Error: could not find react-redux context value; please ensure the component is wrapped in a Provider.
How can I access the redux state inside _app.tsx? This is nextjs by the way.
Your component is not connected to the store. Normally this package https://github.com/kirill-konshin/next-redux-wrapper is used to wrap next.js. Once you created wrapper, you have to wrap _app.jx
export default wrapper.withRedux(MyApp);
Now you can use useSelector to access store within any component
import { useSelector } from "react-redux";

React Native Error: The component for route must be a React component

I'm trying to create a basic setup for react navigation, but for some reason, when I go to view the project, I get a blank screen and an error in terminal that says:
Error: The component for route 'screens' must be a React component. For example:
import MyScreen from './MyScreen';
...
screens: MyScreen,
}
You can also use a navigator:
import MyNavigator from './MyNavigator';
...
screens: MyNavigator,
}
I've looked at other Stack Overflow solutions, but none of them seem to apply in my case, so, is there something else I'm doing wrong here?
My App.js (Also importing fonts here, but these worked, it seems to be an issue with the routing)
import React, {useState} from 'react';
import * as Font from 'expo-font';
import AppLoading from 'expo-app-loading';
import Navigator from './routes/homeStack';
const getFonts = () => Font.loadAsync({
'raleway-regular': require('./assets/fonts/Raleway-Regular.ttf'),
'raleway-bold': require('./assets/fonts/Raleway-Bold.ttf')
});
export default function App() {
const [fontsLoaded, setFontsLoaded] = useState(false);
if (fontsLoaded) {
return (
<Navigator />
);
} else {
return (
<AppLoading
startAsync= {getFonts}
onFinish= {()=> setFontsLoaded(true)}
onError= {()=> console.log('error')}
/>
);
}
}
homeStack.js
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
import Home from '../screens/home';
import Scanner from '../screens/scanner';
const screens = {
Home: {
screen: Home
},
Scanner: {
screen: Scanner
},
};
const HomeStack = createStackNavigator({screens});
export default createAppContainer(HomeStack);
home.js
import React from 'react';
import { StyleSheet, View, Text, } from 'react-native';
import { globalStyles } from '../styles/global';
export default function Home() {
return (
<View style={globalStyles.container}>
<Text style={globalStyles.titleText}>Home Screen</Text>
</View>
);
}
scanner.js
import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
import { globalStyles } from '../styles/global';
export default function Scanner() {
return (
<View style={globalStyles.container}>
<Text>About Screen</Text>
</View>
);
}
My file directory
Any help would be much appreciated!
The video you are following along with is really old and probably not up to date anymore. Please follow the installation guides and then follow along this guide. That should get you up and running in minutes.

Next.js - How do I use Provider to Wrap Routes and use Context with Hooks

I wrote code similar to the following in create-react-app and I want to know the equivalent for next.js. The code below is my attempt at having a global Context that is available to all pages. The Provider wraps the Links. I get no errors. The problem is inside the about page the console.log(state) returns undefined when I expect the Context state. How do I fix this?
Thank you.
pages/index.js
import Link from "next/link";
import {Provider} from './Context';
function Index(){
return(
<div>
<Provider>
<ul>
<li><Link href="/"><a>Home</a></Link></li>
<li><Link href="/about"><a>About</a></Link></li>
</ul>
</Provider>
</div>
)
}
export default Index;
pages/about.js
import { useRouter } from 'next/router';
import {Context} from './Context';
import {useContext} from 'react';
const About= () => {
const data = useContext(Context);
console.log(data)
return (
<div>
<p>This is the blog post content.</p>
</div>
);
};
export default About;
pages/Context.js
import React, {createContext, useState, useEffect}from 'react';
let Context = createContext();
function Provider(props){
const initialState = {
userID: false,
user:undefined,
loading: true,
authenticated:false
}
const [state,updateState] = useState(initialState)
return(
<Context.Provider value={{
state:state
}}>
{props.children}
</Context.Provider>
)
}
const Consumer = Context.Consumer;
export {Provider, Consumer, Context}
You can move <Provider> into a custom <App> component which initializes each page.
pages/_app.js
import React from 'react'
import App from 'next/app'
import {Provider} from './Context';
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return <Provider><Component {...pageProps} /></Provider>
}
}
export default MyApp
More info here
The idea is you need to have a parent Provider anywhere in your tree to consume a context. In your case, you Provider is not a parent of About component. You need to move your Provider to _app.js like this

createStore function returns undefined store object

I am very new to React Native and in the process of creating some sample apps. So following a tutorial app, i was trying to create a Taxi Booking App that has redux store involved in it.
So my App.js file looks as below:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import Root from "./src/main";
export default class TaxiApp extends Component {
render() {
return (
<View style={styles.container}>
<Root {...this.props}/>
</View>
);
}
}
The main.js file is as follows:
import React from "react";
import createStore from "./store/createStore";
import AppContainer from "./AppContainer";
export default class Root extends React.Component{
renderApp(){
const initialState = window.___INITIAL_STATE__;
const store = createStore(initialState);
return(
<AppContainer store={store}/>
);
}
render(){
return this.renderApp();
}
}
The AppContainer component is as follows:
import React, {Component, PropTypes} from "react";
import {Router} from "react-native-router-flux";
import {Provider} from "react-redux";
import scenes from "../routes/scenes";
export default class AppContainer extends Component{
static propTypes = {
store : PropTypes.object.isRequired
}
render(){
return(
<Provider store={this.props.store}>
<Router scenes={scenes}/>
</Provider>
)
}
}
The createStore() function for the Root component is as follows:
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import makeRootReducer from "./reducers";
import { createLogger } from "redux-logger";
import createSocketIoMiddleware from "redux-socket.io";
import io from "socket.io-client/dist/socket.io";
let socket = io("http://localhost:3000", {jsonp:false});
let socketIoMiddleware = createSocketIoMiddleware(socket, "server/");
const log = createLogger({ diff: true, collapsed: true });
// a function which can create our store and auto-persist the data
export default (initialState = {}) => {
// ======================================================
// Middleware Configuration
// ======================================================
const middleware = [thunk, log, socketIoMiddleware];
// ======================================================
// Store Enhancers
// ======================================================
const enhancers = [];
// ======================================================
// Store Instantiation
// ======================================================
const store = createStore(
makeRootReducer(),
initialState,
compose(
applyMiddleware(...middleware),
...enhancers
)
);
return store;
};
On trying to run this in the android emulator I am getting the following error:
undefined is not an object(evaluating '_react.PropTypes.object')
It would be great if someone could help. Thanks in advance!!!
You need to do the following
import PropTypes from 'prop-types';
remove import proptypes from the react package

How to solve "Unable to resolve module..." error with react-native?

I am trying to learn to use react native and am following along with this YouTube tutorial. I have encountered an error stating the following, "Unable to resolve the module ... from ...: could not resolve ... as a file nor folder." I am fairly certain that the file path used is correct and I have followed the video very closely, and it appears to work in this video. Any help with this would be greatly appreciated as I am unfamiliar with using components in react.
index.js
import React, {Component} from 'react';
import { AppRegistry, Text, View } from 'react-native';
import App from './App';
import Component1 from './app/components/Component1/Component1';
export default class myapp extends Component {
render() {
return(
<View>
<Component1 />
</View>
);
}
constructor() {
super();
}
}
AppRegistry.registerComponent('myapp', () => myapp);
component1.js
import React, {Component} from 'react';
import { AppRegistry, Text, View } from 'react-native';
import App from './App';
export default class Component1 extends Component {
render() {
return(
<View>
<Text>This is Component 1.</Text>
</View>
);
}
constructor() {
super();
}
}
AppRegistry.registerComponent('Component1', () => Component1);
Try this path to your component
import Component1 from './app/components/Component1/component1';

Categories

Resources