Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UseSelector State is Undefined

The page does not render, citing TypeError: state is undefined, tracing back to this line in SelectForm.js: const filter = useSelector(state => state.filter);.

I've spent hours trying to figure out what I'm doing wrong. I've tried createSelector but that didn't work. I've tried dispatching a "Fetch Initial State" action, and that didn't work. The component is wrapped in provider tags. I'm not sure why I don't have access to the state. At this point I'm unable to see any flaws I've been looking at it for so long.

Code Snippets

reducer.js

let initialState = {
    filter: {
        country: null,
        state: null,
        level: null,
        team: null
    },

    isDBConnecting: false, 
    isDBConnected: false, 
    isDBError: false 
}

const SelectorReducer = (state=initialState, action) => {
    switch (action.type) {        
        case 'DB_CONNECT_INIT':
            return {
                ...state,
                isDBConnecting: true,
                isDBConnected: false,
                isDBError: false,
            };
...
...
}

export default SelectorReducer;

actions.js

export const initializeDBConnection = () => {
    return {
        type: 'DB_CONNECT_INIT'
    }
};

ParentComponent.js

import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux'; //import provider to provide component access to the state

//Component imports
import SelectForm from './components/SelectForm'
import SelectorReducer from '.../reducer.js'

const SelectorStore = createStore(SelectorReducer);

const ParentComponent = () => {

    return (
        <div className="page-container">
            <div id="carousel">
                <div id="wrapper">
                    <Provider store={SelectorStore}>
                        <SelectForm />
                    </Provider>
                </div>
            </div>
    </div>
    )
}

SelectForm.js (Child Component, wrapped in Provider tags above)

//IMPORTS
import React from 'react'; //import react
import { useSelector, useDispatch } from 'react-redux';

//COMPONENT IMPORTS
import FormGroup from '../FormGroup';
import { * as actions } from '.../actions.js';

const SelectForm = (props) => {

    //STATEFUL IMPORTS
    //filter
    const filter = useSelector(state => state.filter);
like image 986
Xonu Avatar asked May 31 '20 02:05

Xonu


1 Answers

Credit to @NicholasTower for the answer in the comments. My reducer did not have a default case in which

default: return state

Putting that in solved the issue.

like image 106
Xonu Avatar answered Sep 27 '22 23:09

Xonu