0

Hi I am using trufflebox boilerplate react-auth-box. Created a new component called Foo where I am trying to access the web3 object that has been mapped from Store to this.props.

However the console.log(this.props.web3) is showing {web3Instance: null}. What should we do?

src/Foo.js

import React, { Component } from 'react';
import { connect } from 'react-redux';


class Foo extends Component {

    componentWillMount() {
        console.log(this.props.web3)               // {web3Instance: null}
    }

    render() {
        return ( <div>foo</div> )
    }
}


function mapStateToProps(state) {
    return {
        web3: state.web3
    }
}


export default connect(mapStateToProps)(Factory);

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import { Provider } from 'react-redux'
import { syncHistoryWithStore } from 'react-router-redux'
import { UserIsAuthenticated, UserIsNotAuthenticated } from './util/wrappers.js'
import getWeb3 from './util/web3/getWeb3'

// Layouts
import App from './App'
import Home from './layouts/home/Home'
import Dashboard from './layouts/dashboard/Dashboard'
import SignUp from './user/layouts/signup/SignUp'
import Profile from './user/layouts/profile/Profile'
import Foo from './Foo'

// Redux Store
import store from './store'

// Initialize react-router-redux.
const history = syncHistoryWithStore(browserHistory, store)

// Initialize web3 and set in Redux.
getWeb3
.then(results => {
  console.log('Web3 initialized!')
})
.catch(() => {
  console.log('Error in web3 initialization.')
})

ReactDOM.render((
    <Provider store={store}>
      <Router history={history}>
        <Route path="/" component={App}>
          <IndexRoute component={Home} />
          <Route path="dashboard" component={UserIsAuthenticated(Dashboard)} />
          <Route path="signup" component={UserIsNotAuthenticated(SignUp)} />
          <Route path="profile" component={UserIsAuthenticated(Profile)} />
          <Route path="foo" component={Foo} />
        </Route>
      </Router>
    </Provider>
  ),
  document.getElementById('root')
)

1 Answer 1

0

Your ReactDOM.render is happening before the getWeb3 is done.

use your store to dispatch an action such as

{
  type:  WEB3_LOADED,
  payload: results
}

and add a reducer called web3 that injects the action's payload into the state as web3

const reducer = (state = { web3: null }, action) => {
   switch(action.type) {
      case WEB3_LOADED: return { web3: action.payload }
      default: return state
   }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.