4

Curious what's the best way to access and pass a web3 contract instance provided by MetaMask between components when using react-redux.

At this point, I'm tempted to do the following for both web3 and the contract:

const mapDispatchToProps = dispatch => ({
    setWeb3: (web3) => {
        dispatch({
            type: 'WEB3',
            value: web3
        })
    },    
    setContract: (contractInstance) => {
        dispatch({
            type: 'CONTRACT',
            value: contractInstance
        })
    },  
});

With the following initialization in ComponentDidMount

 setInterval(() => {
                web3js.eth.getAccounts((error, accounts) => {
                    if (accounts.length > 0) {
                        this.props.setWeb3(web3js);

                        //Do contract initialization...
                        this.props.setContract(contractInstance);
                 }
                });
            }, 2500);

I know that it's not best practice to be putting non-JSON, non-serializable data into the props.

Suggestions for a best practice? I suppose an alternative would be to create a separate .js file with getter/setters for the instances. Am I overthinking this?

Thanks!

1

not sure what you ended up doing here, but when I ran into a similar issue, I decided to put web3 into my selectors. That was important because the Provider URL could change over time, so I wanted to make sure that Web3 always had the most up-to-date value from the Redux store. The big perk of doing this as a selector is that you don't need to worry about any imperative update logic -- the selector just always returns an up-to-date web3.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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