swimisbell
swimisbell

Reputation: 1591

MobX with React Native: store is undefined

This is my first go at using MobX so this may be a simpler problem than I imagine, but I'm not getting any errors with the things I've tried; the store is simply undefined wherever I try to use it. I've tried both importing the store directly into components and passing props from the main file (also with , but I'm not sure if I used that right). I've experimented with several different .babelrc file settings as well, but that doesn't seem to be an issue.

Here is the UserStore:

import React from 'react';
import { observable } from 'mobx';

class UserStore {
  @observable info = {
    username: "bob",
    password: "secret",
    email: "[email protected]"
  }
}

const userStore = new UserStore()
export default userStore;

Here is a simplified App.js:

import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Profile from './app/Profile.js';
import { UserStore } from './app/UserStore.js';

export default class App extends Component {
  constructor(){
    super();
    this.state = {
      page: 'Profile',
    }
  }

  changePage(){
    switch (this.state.page) {
      case "Profile":
        return <Profile logout={this.logout.bind(this)} userStore={UserStore}/>;
    }
  }

  render() {
    return (
      <View>
        {this.changePage()}
      </View>
    );
  }
}

And here is a simplified Profile.js:

import React, { Component } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { observer } from 'mobx-react/native';

@observer
export default class Profile extends Component {

  render() {
    console.log(this.props.userStore);
    return (
      <View>
        <Text>Profile Page</Text>
        <Text>username: {props from store go here}</Text>
        <Text>password: {props from store go here}</Text>
        <Text>email: {props from store go here}</Text>
      </View>
    );
  }
}

All I'm trying to do right now is get the pre-defined observable "info" object from the store to the Profile.js component and display that information. This is being way more difficult than it should be - any insight is greatly appreciated!

Upvotes: 4

Views: 3959

Answers (1)

max23_
max23_

Reputation: 6689

Since you declared export default userStore; in UserStore.js

Try changing the way you import in App.js by removing the {}:

import UserStore from './app/UserStore.js';

{} is needed only if you want to do a named import. Here is a good read if you want to know more.

Upvotes: 6

Related Questions