React - Redux Error: Element type is invalid after connect

Viewed 152

I'm trying to learn to React - Redux. I created an Exam Component like the following:

class ExamHome extends React.Component {

    constructor(props) {
        super(props)
    }

    render() {
        return (
            <TabPane>
                <Exam />
            </TabPane>
        )
    }
}

export default ExamHome;

I created a Exam React component like the following:

class Exam extends React.Component {

    constructor(props) {
        super(props)
    }

    render() {
        return (
            "hello"
        )
    }
}

const mapStateToProps = state => {
    return {
        examUrl: state.examApp.examUrl
    }
};

export default connect(mapStateToProps, {
    showExam
})(Exam);

Here's my reducer:

let initialState = {
    examUrl: null
}

const exam = (state = initialState, action) => {
    switch (action.type) {
        case "SHOW_EXAM":
            return { ...state, examUrl: action.examToken }

        default:
            return state
    }
};

export default exam

And here's my action:

export const showExam = t => {
    return dispatch => dispatch({
        type : "SHOW_EXAM", examToken : t
    })
}

It works fine if i remove connect If I add connect i get the following error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of ExamHome.

I tried all the possible solutions I found in Stackoverflow but none of them working. Thanks for your help.

Edit:

Here's rootReducer.js

import { combineReducers } from "redux"
import { connectRouter } from 'connected-react-router'
import customizer from "./customizer/"
import auth from "./auth/"
import navbar from "./navbar/Index"
import exam from "./exam/exam"

const rootReducer = (history) => combineReducers({
  customizer: customizer,
  auth: auth,
  navbar: navbar,
  exam: exam,
  router: connectRouter(history)
})

export default rootReducer
1 Answers

You just need to define your dispatch and return to connect function and run it using componentDidMount:

import * as Actions from "path of showExam, Actions file only";

class Exam extends React.Component {

componentDidMount() {
    props.onShowExam("any value you want in default");
  }

    constructor(props) {
        super(props)
    ....
}

const mapStateToProps = state => {
    return {
        examUrl: state.examApp.examUrl
    }
};

const mapDispatchToProps = dispatch => {
    return {
         onShowExam: (val) => dispatch(Actions.showExam(val))
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Exam);
Related