MobX + React Native : way to inject stores - javascript

I'm trying to work with MobX for a new project.
I started it on May 2017, and everything was working well. I had to stop, and now I go on developing it. I had to make an npm install to manage making it working, but now, I have some problem with stores...
I rely on this tutorial for the structure : https://blog.callstack.io/write-react-native-apps-in-2017-style-with-mobx-e2dffc209fcb
This is my structure :
Main index.js
import { Provider } from 'mobx-react';
import Stack from './router';
import stores from './stores';
export default class App extends Component {
render() {
return (
<Provider {...stores}>
<Stack />
</Provider>
);
}
}
Index.js of my stores in ./stores/index.js
import ChatStore from './ChatStore';
import UserStore from './UserStore';
export default {
UserStore: new UserStore(),
ChatStore: new ChatStore(),
};
./stores/UserStore.js (important parts)
import { observer, inject } from 'mobx-react';
import {autobind} from 'core-decorators';
...
#inject(['ChatStore'])
#observer
#autobind
export default class UserStore {
#observable isAuthenticated = false;
#observable isConnecting = false;
#observable user = null;
#observable messages = [];
#observable hasMoreMessages = false;
#observable skip = 0;
...
login() {
const payload = {
strategy: 'local',
material_id: DeviceInfo.getManufacturer(),
password: DeviceInfo.getManufacturer()
};
return this.authenticate(payload);
}
...
Now, for components part :
Router.js
import { StackNavigator } from 'react-navigation';
import Home from './containers/Home';
const stackNavigatorConfig = {
initialRouteName: 'Home',
};
export default StackNavigator({
Home: {
screen: Home,
},
}, stackNavigatorConfig);
./containers/Home.js
import React, { Component } from 'react';
import { AsyncStorage } from 'react-native';
import { observable } from 'mobx';
import { observer, inject } from 'mobx-react';
#inject('UserStore')
#observer
export default class Home extends Component {
props: Props;
...
render() {
this.props.UserStore.login().catch(error => {
console.log('LOGIN', 'ERROR', JSON.stringify(error), error.message);
});
return {
...
}
}
And then, I get an error :
So, I sum up :
I use <Provider> from MobX, to give all my stores to my app
Then, I get the Store I want in my component with #inject
I use it as a props, using this.props.UserStore...
But it does not work. I rely on this tutorial for the structure : https://blog.callstack.io/write-react-native-apps-in-2017-style-with-mobx-e2dffc209fcb
Maybe there was an update between May 2017 and today, that makes things different... It was working well on May 2017.
I think this is a dummy error, but I can't find which one...

Everything looks good except the decorators on your UserStore class: #inject(['ChatStore']) #observer #autobind. #inject(['ChatStore']) #observer is used on React components, #autobind might still work as intended.
It should work if you remove those.

maybe worth using #action from mobx

Related

React Router & Global Context

I'm building an e-commerce website with React (my first ever React project) and I'm using React router to manage my pages.
I've got the following component tree structure:
<Router>
<BrowserRouter>
<Router>
<withRouter(Base)>
<Route>
<Base>
<BaseProvider>
<Context.Provider>
<Header>
<PageContent>
The standard React Router structure basically, and withRouter I've got the following:
Base.js
import React, { Component } from 'react';
import { withRouter } from 'react-router';
import { Header } from './Header';
import { Footer } from './Footer';
import Provider from '../../BaseProvider';
class Base extends Component {
render() {
return (
<Provider>
<Header/>
<div className="container">{this.props.children}</div>
<Footer />
</Provider>
);
}
}
BaseProvider.js
import React, { Component, createContext } from 'react';
const Context = createContext();
const { Provider, Consumer } = Context;
class BaseProvider extends Component {
state = {
cart: [],
basketTotal: 0,
priceTotal: 0,
};
addProductToCart = product => {
const cart = { ...this.state.cart };
cart[product.id] = product;
this.setState({ cart, basketTotal: Object.keys(cart).length });
};
render() {
return (
<Provider
value={{ state: this.state, addProductToCart: this.addProductToCart }}
>
{this.props.children}
</Provider>
);
}
}
export { Consumer };
export default BaseProvider;
This gives me a template essentially, so I just the children pages without having to include Header and Footer each time.
If I want to use my global context I'm having to import it each time, and it seems like I've done something wrong as surely I should be able to use this on any page since it's exported in BaseProvider?
If I was to visit the About page, I'd get the same component structure, but no access to the consumer without using:
import { Consumer } from '../../BaseProvider';
Why do I have to do this for each file even though it's exported and at the top level of my BaseProvider? It just seems such a bad pattern that I'd have to import it into about 20 files...
Without importing it, I just get:
Line 67: 'Consumer' is not defined no-undef
I tried just adding the contextType to base but I get: Warning: withRouter(Base): Function components do not support contextType.
Base.contextType = Consumer;
I feel like I've just implemented this wrong as surely this pattern should work a lot better.
I'd recommend using a Higher Order Component - a component that wraps other components with additional state or functionality.
const CartConsumer = Component => {
return class extends React.Component {
render() {
return (
<MyContext.Consumer>
<Component />
</MyContext.Consumer>
)
}
}
}
Then in any component where you'd like to use it, simply wrap in the export statement:
export default CartConsumer(ComponentWithContext)
This does not avoid importing completely, but it's far more minimal than using the consumer directly.

Unidirectional Data Flow in React with MobX

I'm trying to setup a project architecture using MobX and React and was wondering if doing this following would be considered "not bad". I don't want this question to end up being another "this is a matter of personal preference and so this question doesn't belong here... We can all agree that some things really are bad.
So I'm thinking of only having a single Store.js file that looks something like this:
import { observable, action, useStrict } from 'mobx';
useStrict(true);
export const state = observable({
title: ''
});
export const actions = {
setTitle: action((title) => {
state.title = title;
})
};
Note: that all application state will be in state, there will only be a single store.
I then use state in my root component a.k.a App.js like so:
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { state } from './Store';
import DisplayTitle from './components/DisplayTitle/DisplayTitle';
import SetTitle from './components/SetTitle/SetTitle';
class App extends Component {
render() {
return (
<div className="App">
<DisplayTitle title={state.title}/>
<SetTitle />
</div>
);
}
}
export default observer(App);
I'll obviously have a whole bunch of components in my app, but none of the components will ever read state directly from Store.js. Only my App.js will import the state and pass it down the component tree.
Another note: I'm not so sure anymore why other components can't read the state directly from Store.js...
This is the case with the DisplayTitle component:
import React, { Component } from 'react';
class DisplayTitle extends Component {
render () {
return (
<h1>{this.props.title}</h1>
);
}
}
export default DisplayTitle;
But, even though no other components can directly import state (except App.js), any component can import actions from Store.js in order to mutate the state.
For example in the SetTitle component:
import React, { Component } from 'react';
import { actions } from './../../Store';
class SetTitle extends Component {
updateTitle (e) {
actions.setTitle(e.currentTarget.value);
}
render () {
return (
<input onChange={this.updateTitle} type='text'/>
);
}
}
export default SetTitle;
Are there any flaws or other obvious reasons why this approach wouldn't be the best route to go? I'd love any and all feedback!
you are missing a few things
at root level:
import { Provider } from 'mobx-react'
...
<Provider state={state}>
<Other stuff />
</Provider>
At component level:
import { inject } from 'mobx-react'
#inject('state')
class Foo ... {
handleClick(){
this.props.state.setTitle('foo')
}
render(){
return <div onClick={() => this.handleClick()}>{this.props.state.title}</div>
}
}
You can stick only the interface actions={actions} in your provider and inject that, ensuring children can call your API methods to mutate state and have it flow from bottom up. Though if you were to mutate it direct, no side effects will happen because all components willReact and update in your render tree - flux is cleaner to reason about.

Uncaught Error: Could not find "store" in either the context or props of Connect(Form())

I'am using redux, react-router-redux and redux-form in my code. Code has a Provider, Connected router and Mini component. Mini component includes Switch and some components, which depends on route.
Index.js
...
import { Provider } from 'react-redux'
import { ConnectedRouter, routerMiddleware } from 'react-router-redux'
import createBrowserHistory from 'history/createBrowserHistory'
import Reducers from './reducers'
const history = createBrowserHistory({ basename: 'mini' })
const middlewareRouter = routerMiddleware(history)
const store = createStore(Reducers, applyMiddleware(middlewareRouter))
render(<Provider store={store}>
<ConnectedRouter history={history}>
<Mini/>
</ConnectedRouter>
</Provider>, document.getElementById('root'))
Mini.js
import React, { Component } from 'react'
import { Switch, Route } from 'react-router-dom'
...
import NavigationContainer from './containers/navigation'
import CategoryContainer from './containers/category'
class Mini extends Component {
render () {
return (<main>
<Switch>
<Route path="/navigation" component={NavigationContainer}/>
<Route path="/category" component={CategoryContainer}/>
...
</Switch>
<LoadContainer/>
<div id="form"></div>
</main>)
}
}
All components in Switch section has a button. Clicking on the button can render a form.
...
import FormCreate from './formcreate'
class Topbar extends Component {
constructor (props) {
super(props)
this.handleClickCreate = this.handleClickCreate.bind(this)
}
handleClickCreate (e) {
e.preventDefault()
render(<FormCreate/>, document.getElementById('form'))
}
...
}
But when I click on button error appear Uncaught Error: Could not find "store" in either the context or props of "Connect(Form(FormCreate))"
How can I fix the problem? Thanks in advance!
PS Reducers.js
import { combineReducers } from 'redux'
import { routerReducer as reducerRouter } from 'react-router-redux'
import { reducer as reducerForm } from 'redux-form'
const Reducers = combineReducers({
...
router: reducerRouter,
form: reducerForm
})
PSS FormCreate.js
import React from 'react'
import { Field, reduxForm } from 'redux-form'
...
const FormCreate = (props) => {
const { error, handleSubmit, pristine, reset, submitting } = props
return (
...
)
}
export default reduxForm({
form: 'create',
validate
}) (FormCreate)
I think the problem here is that you are trying to render FormCreate create another app within html element form that does not have access to the redux store, resulting in the error that you see.
What I would do is set up a reducer that handle whether or not I should render FormCreate then render it in component in your app like in LoadContainer.
Topbar.js
class Topbar extends Component {
constructor (props) {
super(props)
this.handleClickCreate = this.handleClickCreate.bind(this)
}
handleClickCreate (e) {
e.preventDefault()
// dispatch action to reducer to tell store to display FormCreate
}
...
}
LoadContainer.js
class LoadContainer extends Component {
// ... rest of code
render() {
// get shouldDisplayForm from redux store
const { shouldDisplayForm } = this.props;
return (
//... rest of component
{ shouldDisplayForm && <FormCreate> }
);
}
}
Alternatively, if you want to render FormCreate in html element 'form', you can put the store in a file so that you can require it in many files. Then render FormCreate with Provider like what you've done Index.js.

react-redux nested component not ReactClass in parent?

I am a bit new to react and redux, but made quite a lot of progress.
I am using redux connect to map state to props. Was working like charm, until I got this situation:
Parent component is using mapStateToProps, and here is the source code for it:
import React from 'react';
import { connect } from 'react-redux'
import { NestedComponent } from './NestedComponent'
class ParentElement extends React.Component {
render() {
return (
<div className="App">
<NestedComponent/>
</div>
);
}
}
const mapStateToProps = state => {
const { questions } = state
return {
questions
}
}
ParentElement.contextTypes = {
router: React.PropTypes.object.isRequired
}
export default connect(mapStateToProps)(ParentElement)
Here is the code for the nested element:
import React from 'react';
import { connect } from 'react-redux'
class NestedComponent extends React.Component {
render() {
return (
<div> I am nested</div>
);
}
};
const mapStateToProps = state => {
const { questions } = state
return {
questions
}
}
NestedComponent.contextTypes = {
router: React.PropTypes.object.isRequired
}
export default connect(mapStateToProps)(NestedComponent)
When I try to show the parent element, I get this error:
Warning: React.createElement: type should not be null, undefined,
boolean, or number. It should be a string (for DOM elements) or a
ReactClass (for composite components). Check the render method of
ParentElement.
What am I missing / doing wrong?
Import header file like this:-
import NestedComponent from './NestedComponent'
Without braces.
When a class is exported as a default then it is imported without braces because there is only one default class in a file but, when the class is exported without default you have to import it with braces because there can be more than one class with export keywords in a file (es6 conventions).

Show username in Meteor React component

One of my React component is my main layout, where I display a nav bar with the currently logged-in user. The problem is that Meteor.user() is undefined when the Component is first rendered. How would I go and properly render my nav bar once the user object has been loaded/published?
MainLayout.jsx
import React, { Component } from 'react';
export default class MainLayout extends Component {
render() {
return (<div>{ Meteor.user().username }</div>);
}
}
Thanks.
Meteor.user() should be part of container component. react-meteor-data package should be added to the project.
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import MainLayout from './mainLayout';
export default MainLayoutContainer = createContainer(({ params }) => {
return {
user: Meteor.user(),
};
}, MainLayout);
The user will be available as props in the MainLayout component.
To use data from a Meteor collection inside a React component, we can use an Atmosphere package react-meteor-data which allows us to create a "data container" to feed Meteor's reactive data into React's component hierarchy.
meteor add react-meteor-data
import React, { Component, PropTypes } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
class MainLayout extends Component {
render() {
return (<div>{ this.props.user.username }</div>);
}
}
export default MainLayoutContainer createContainer(() => {
return {
user: Meteor.user()
};
}, MainLayout);

Categories