Thiago Loddi
Thiago Loddi

Reputation: 2340

Invariant Violation when using react-redux connect with react-native

I started building a react-native application and I want to add redux into it. I have used redux many times with react-dom and never had any problems. Now with react-native I can't make it work.

I started a very simple boilerplate application, but when I add the connect HOC to my component I get to following error:

enter image description here

This is the code for my component:

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createStore, combineReducers } from 'redux';
import { connect } from 'react-redux';
import { View } from 'react-native';

const mainReducer = (state = { msg: 'Hello World!' }, action) => {
    switch(action.type) {
        default: return state;
    }
};

const store = createStore(combineReducers({ mainReducer }));

class Main extends Component {
    render() {
        console.log('props: ', this.props);
        return (
            <View>{this.props.msg}</View>
        );
    }
}

const MainWithRedux = connect(state => ({ msg: state.msg }))(Main);
console.log('MainWithRedux: ', MainWithRedux);

export default class App extends Component {
    render() {
        return (
            <Provider store={store}>
                <MainWithRedux />
            </Provider>
        );
    }
}

From the console.log I can see that the connect hoc is indeed returning an object, not a component:

enter image description here

I created my project using react-native-create-app and these are my dependencies:

"react": "16.6.3",
"react-native": "0.57.4",
"react-redux": "^7.0.2",
"redux": "^4.0.1"

Am I missing something? How can I properly integrate react-redux with react-native?

Upvotes: 2

Views: 1408

Answers (3)

Highspeed
Highspeed

Reputation: 442

Just throwing this out there just in case, because I struggled through this very cryptic error myself. I ended up finding out that I imported Provider from react-navigation instead of react-redux.

Upvotes: 0

ApplePearPerson
ApplePearPerson

Reputation: 4439

Anyone coming across this issue, I believe this happens because of the react-native and react-redux versions. See this for a tiny bit more information: https://github.com/reduxjs/react-redux/issues/1274

I had this error on [email protected] and [email protected]. I'm currently not in a position to upgrade my react-native version so I was left with having to downgrade my react-redux version. I downgraded it to [email protected] and everything seems to work now.

Upvotes: 1

qadir husainee
qadir husainee

Reputation: 132

While using connect you are not specifying reducer from which you need to import 'msg'.

const MainWithRedux = connect(state => ({ msg: state.mainReducer.msg }))(Main);

Might be this can resolve your issue.

Upvotes: 0

Related Questions