Search code examples
typescriptreact-hooks

React Component goes blank when wrapped in StoreProvider


Hi I have a very simple react component which works

import React, {Fragment} from 'react';

export default function App() : JSX.Element {
    return (
        <Fragment>
            <h1>Rick and Morty</h1>
            <p>Pick your favorite episode!!!</p>
        </Fragment>
    )
}

I render this using RenderDOM.render(<App/>, document.getElementById('root'))

Now I change my Render method to

import {StoreProvider} from './Store';
import App from './App';
ReactDOM.render(<StoreProvider><App/></StoreProvider>, document.getElementById('root'););

and My Store looks like

import React, {useReducer} from 'react';
interface IState {
    episodes: string[],
    favorites: string[]
};

interface IAction {
    type: string,
    payload: any
};

const initialState : IState = {
    episodes: [],
    favorites: []
};
export const Store = React.createContext<IState | any>(initialState);
function reducer(state: IState, action: IAction): IState {
    switch(action.type) {
        case 'FETCH_DATA':
            return state;
        default:
            return state;
    }
}
export function StoreProvider(props: any): JSX.Element {
    const [state, dispatch] = useReducer(reducer, initialState);
    return <Store.Provider value={{state, dispatch}}>{props.childen}</Store.Provider>
}

As soon as I do it my react component goes blank and there are no error messages or anything in the developer console or the webpack-dev-server.

Why did it go blank? I am not able to troubleshoot this because there is absolutely no error messages

My repo is here https://github.com/abhsrivastava/react-rick-and-morty


Solution

  • Shouldn't it be props.children, instead of props.childen in StoreProvider render function?

    You could've added prop types to StoreProvider to prevent this from happening

    type IStoreProviderProps = { children: React.ReactNode }
    export function StoreProvider({ children }: IStoreProviderProps): JSX.Element {
        const [state, dispatch] = useReducer(reducer, initialState);
        return <Store.Provider value={{state, dispatch}}>{children}</Store.Provider>
    }