Home > Net >  Error when wrapping App with Redux Provider
Error when wrapping App with Redux Provider

Time:11-12

This is the error I get when I try to wrap my TypeScript React application using Redux:

Error: Objects are not valid as a React child (found: object with keys {children}). If you meant to render a collection of children, use an array instead.

Here is index.tsx:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import StoreWrapper from './Store/StoreWrapper/StoreWrapper';


ReactDOM.render(
    <React.StrictMode>
        <StoreWrapper>
            <App />
        </StoreWrapper>
    </React.StrictMode>,
    document.getElementById('root')
);
reportWebVitals();

This is StoreWrapper.tsx:

import React from 'react';
import { Provider } from 'react-redux';
import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import thunk from 'redux-thunk';

import AuthReducer from '../Reducers/Authentication';

const composeEnhancers =
    (window as any).__REDUX_ DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const rootReducer = combineReducers({
    auth: AuthReducer
});

const store = createStore(
    rootReducer,
    composeEnhancers(applyMiddleware(thunk))
);

const StoreWrapper = (children: any) => {
    return <Provider store={ store }>{ children }</Provider>;
};

export default StoreWrapper;

This is the Authentication reducer:

import * as actionTypes from '../Actions/actionTypes';


const init  = {
    token: null,
    userId: null,
    loading: false,
    error: null
};

const reducer  = (
    state = init,
    action: any 
) => {
    switch (action.type) {
    case actionTypes.AUTH_INIT:
        return {
            ...state,
            error: null,
            loading: true
        };

    case actionTypes.AUTH_SUCCESS:
        return {
            ...state,
            error: null,
            loading: false,
            token: action.token,
            userId: action.userId
        };

    case actionTypes.AUTH_FAIL:
        return {
            ...state,
            error: action.error,
            loading: false
        };

    case actionTypes.AUTH_LOGOUT:
        return {
            ...state,
            token: null,
            userId: null
        };

    default:
        return state;
    }
};

export default reducer;

What am I missing?

CodePudding user response:

type Props = {
  children: React.ReactNode
}
const StoreWrapper = ({children}: Props) => {  // You need to destructure props
    return <Provider store={store}>{children}</Provider>;
};
  • Related