Aldo Fiore
Aldo Fiore

Reputation: 1

Connecting Redux to my app at the top level doesn't work

I have been trying to debug this code for a while now, but I can't seem to understand what the problem is here. I am trying to connect my top-level app to the redux store, but I always get an empty store and I can't understand why. Here's the code:

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { App } from './App';
import { Store } from 'redux';
import createStore from './model/configureStore';
import { State } from './model/types';

const store: Store<State> = createStore();

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);

App.tsx

import React from 'react';
import { State } from './model/types';
import { connect } from 'react-redux';

export const App:React.FunctionComponent = (props) => {
    console.log(props);
    return <div>Hello</div>;
};

const mapStateToProps = (state: State) => ({
    isLoading: state.isLoading,
});

export default connect(mapStateToProps)(App);

(The console log above will return an empty object, for some unknown reasons).

loading.ts

import { BooleanAction } from '../utils/redux-utils';

const IS_LOADING = 'IS_LOADING_GENERAL';

export const setIsLoading = (payload: boolean) =>
    <BooleanAction>{
        type: IS_LOADING,
        payload,
    };

const defaultState = true;

export const reducer = (
    state: boolean = defaultState,
    action: BooleanAction
) => {
    switch (action.type) {
        case IS_LOADING:
            return action.payload;
        default:
            return state;
    }
};

combineReducers.ts

import { ReducersMapObject, combineReducers } from 'redux';
import { reducer as isLoading } from './loading';
import { State } from './types';

const reducerMap: ReducersMapObject<State> = {
    isLoading,
};

export default combineReducers<State>(reducerMap);

configureStore.ts

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './combineReducers';

export default () => createStore(rootReducer, applyMiddleware(thunk));

The code seems to be right to me, but it doesn't give me the expected result. Just to make it more confusing, if I don't wrap my app in the <Provider> at the ReactDOM.render() function, everything works, but I want to handle some loading state at the top level, so I need it to work this way.

Thank you in advance!!

Upvotes: 0

Views: 148

Answers (1)

helloitsjoe
helloitsjoe

Reputation: 6529

In index.ts, you're importing the named App component instead of the default connected App:

import { App } from './App';

That should be

import App from './App';

Upvotes: 1

Related Questions