Next.js: Build error // Cannot read property 'store' of null

Created on 10 Nov 2020  Â·  9Comments  Â·  Source: vercel/next.js

Bug report

Describe the bug

The application run fine in dev, but I cant build.
ps: Previous NEXTJS version it was working fine: "next": "^8.1.0",

In the App file I do:
const data = useSelector((state) => state);

➜  next-comidadodia git:(master) ✗ yarn build
yarn run v1.22.10
warning package.json: No license field
$ NODE_ENV=production next build
info  - Creating an optimized production build
info  - Compiled successfully
info  - Collecting page data
[=   ] info  - Generating static pages (0/8)
Error occurred prerendering page "/App". Read more: https://err.sh/next.js/prerender-error
TypeError: Cannot read property 'store' of null
    at useSelector (/Users/cesar.cabral/Projects/next-comidadodia/node_modules/react-redux/lib/hooks/useSelector.js:115:34)
    at App (/Users/cesar.cabral/Projects/next-comidadodia/.next/server/pages/App.js:3765:60)
    at d (/Users/cesar.cabral/Projects/next-comidadodia/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:498)
    at $a (/Users/cesar.cabral/Projects/next-comidadodia/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:39:16)
    at a.b.render (/Users/cesar.cabral/Projects/next-comidadodia/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:44:476)
    at a.b.read (/Users/cesar.cabral/Projects/next-comidadodia/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:44:18)
    at renderToString (/Users/cesar.cabral/Projects/next-comidadodia/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:54:364)
    at Object.renderPage (/Users/cesar.cabral/Projects/next-comidadodia/node_modules/next/dist/next-server/server/render.js:50:851)
    at Function.getInitialProps (/Users/cesar.cabral/Projects/next-comidadodia/.next/server/pages/_document.js:334:19)
    at Function.getInitialProps (/Users/cesar.cabral/Projects/next-comidadodia/.next/server/pages/_document.js:136:85)
info  - Generating static pages (8/8)

> Build error occurred
Error: Export encountered errors on following paths:
    /App
    at exportApp (/Users/cesar.cabral/Projects/next-comidadodia/node_modules/next/dist/export/index.js:25:1103)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async build (/Users/cesar.cabral/Projects/next-comidadodia/node_modules/next/dist/build/index.js:39:69)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Expected behavior

Running without errors.

Screenshots

If applicable, add screenshots to help explain your problem.
image

System information

  • OS: Any
  • Browser Any
  • Version of Next.js: 10
  • Version of Node.js: v12.12.0
please add a complete reproduction bug

All 9 comments

Hi! Could you please provide a complete reproduction of this issue including a repository or code snippets? Thanks!

@jamesmosier

I cant share the repo, but I can share where I create the store: (I removed sensitive informations)

Where I created the store:

import Grid from "@material-ui/core/Grid";

import React, { useEffect } from "react";

import { createStore } from "redux";
import { Provider } from "react-redux";

const store = createStore(reducerData, {});

const Layout = (props) => {
    useEffect(() => {
        if (!window.GA_INITIALIZED) {
            initGA(); // Google Analytics
            window.GA_INITIALIZED = true;
        }

        logPageView();
    });

    return (
        <Provider store={store}>
            <GlobalStyles />
            <Head></Head>
            <Normalize />
            <HeaderSite />
            <CookiesAllow />
            <main className={"c-main"}>
                <Grid container justify="center">
                    <Grid item xs={11} sm={11} md={11} lg={11}>
                        {props.children}
                    </Grid>
                </Grid>
            </main>
            <FooterSite />
        </Provider>
    );
};

export default Layout;

My APP file:

import React, { useState, useEffect } from "react";

import axios from "axios";

import { useSelector, useDispatch } from "react-redux";

import { useRouter } from "next/router";

import { ListPosts, LoaderContent, CmdInstagramBox, DynamicLink } from "./../components/features";
import {
    styleDefaultPageMobile,
    styleDefaultPageDesktop,
    styleTitleArea,
    styleTitleAreaSearch,
    styleAlertDanger,
    styleRecipeTitleMiddleArea,
} from "../components/global-styles";
import useWindowSize from "../components/hooks/useResize";
import { ADD_CATEGORY } from "../components/state/actions";
import HomeSearch from "../components/features/home-search/home-search";

const App = () => {
    const Router = useRouter();
    const [browserWidth] = useWindowSize();

    const data = useSelector((state) => state);
    const dispatch = useDispatch();

    const [initContent, setInitContent] = useState([]);
    const [pageStyle, setPageStyle] = useState({});
    const [searchFor, setSearchFor] = useState("");
    const [searchTotalPages, setSearchTotalPages] = useState(0);
    const [searchList, setSearchList] = useState([]);
    const [searchUrlRequest, setSearchUrlRequest] = useState("");
    const [listCategories, setListCategories] = useState(data.category ? data.category : {});
    const initSearch = Router.query.busca;

    const fetchCategoriesData = async () => {
        if (data.category) return;

        const URL = `${baseURLtoFetch}/categories?per_page=99`;
        const getData = await axios.get(URL);

        setListCategories(getData.data);
        dispatch({
            type: ADD_CATEGORY,
            payload: getData.data,
        });
    };

    const fetchContent = async () => {
        const URL = `${baseURLtoFetch}/posts?per_page=12`;
        const response = await axios.get(URL);
        setInitContent([...response.data]);
    };

    const fetchSearchContent = async (text) => {
        const value = text.replace(" ", "-");
        const URL = `${baseURLtoFetch}/posts?search=${value}`;
        const data = await axios.get(URL);

        if (value.length > 3) {
            history.pushState(null, document.title, `?busca=${value}`);
        } else {
            history.pushState(null, document.title, window.location.origin);
        }

        setSearchList([...data.data]);
        setSearchUrlRequest(URL);
        setSearchTotalPages(data.headers["x-wp-totalpages"]);
    };

    const getSearchData = (param) => {
        const searchTerm = param ? param.replace(/ /g, "+") : "";

        searchTerm.length > 3 ? setSearchFor(searchTerm) : setSearchFor("");

        fetchSearchContent(searchTerm);
    };

    useEffect(() => {
        fetchCategoriesData();
        fetchContent();

        searchFor && searchFor === "" && initSearch.length > 0 && setSearchFor(initSearch);

        browserWidth < 1030
            ? setPageStyle({
                    ...styleDefaultPageMobile,
                    margin: "15vh 0 0vh",
              })
            : setPageStyle({
                    ...styleDefaultPageDesktop,
                    margin: "160px auto 0px",
              });
    }, [searchFor.length, browserWidth]);

    if (!initContent && !listCategories) return <LoaderContent />;

    return (
        <>
            <div style={pageStyle}>
                {searchFor.length === 0 ? (
                    <span
                        style={{
                            background: "url(/static/images/nuts.jpg) center top",
                            backgroundSize: "cover",
                            width: `${browserWidth < 1030 ? "100%" : "60%"}`,
                            height: "10vh",
                            display: "block",
                            maxWidth: "1440px",
                            margin: "0 auto",
                        }}
                    />
                ) : null}

                <HomeSearch initSearch={initSearch} getSearchData={getSearchData} />

                {searchFor.length === 0 ? (
                    <span
                        style={{
                            background: "url(/static/images/nuts.jpg) center bottom",
                            backgroundSize: "cover",
                            width: `${browserWidth < 1030 ? "100%" : "60%"}`,
                            height: "10vh",
                            display: "block",
                            maxWidth: "1440px",
                            margin: "0 auto",
                        }}
                    />
                ) : null}

                {searchFor.length > 0 ? null : (
                    <>
                        <ListCategoriesHome responsiveInfo={browserWidth < 1030} data={listCategories} />
                        <CmdInstagramBox responsiveInfo={browserWidth < 500} />
                    </>
                )}

                {initContent && searchList && searchFor.length > 3 ? (
                    <SearchListPosts
                        setData={searchList}
                        searchFor={searchFor}
                        searchUrl={searchUrlRequest}
                        searchTotalPages={searchTotalPages}
                    />
                ) : (
                    <NormalListPost setData={initContent} searchFor={searchFor} />
                )}
            </div>
        </>
    );
};

export default App;

const ListCategoriesHome = ({ data, responsiveInfo }) => {
    const objDecocator = {
        acompanhamentos: "Ideias simples para",
        aperitivos: "Sugestões de",
        bolos_e_tortas: "Fazer surpresas com",
        carnes_e_pratos_principais: "Receitas praticas para",
        dia_das_maes: "Receitas para completar o",
        doces_e_sobremesas: "Que tal receitas de",
        festa_junina: "Por que eu adoro",
        lanches: "Dicas de",
        microondas_light: "Quero algo rápido usando",
        molhos_e_saladas: "Receitas de",
        natal: "Dicas excelentes para o",
        pascoa: "O que fazer para a",
        sopas_e_cremes: "Eu adoro",
        sucos_e_vitaminas: "Sugestões de",
        vegetariana: "Receitas para uma vida",
    };

    return (
        <>
            <div>
                <ul
                    style={{
                        margin: 0,
                        padding: 0,
                        overflow: "hidden",
                        textAlign: "center",
                    }}
                >
                    {Object.keys(data).map((item, key) => {
                        if (
                            data[item].name === "publieditorial" ||
                            data[item].name === "Sem categoria" ||
                            data[item].name === "Dicas de cozinha" ||
                            data[item].name === "Comidas da Copa"
                        )
                            return;

                        const decoratorName = data[item].slug.replace(/-/g, "_");

                        return (
                            <li
                                style={{
                                    listStyle: "none",
                                    width: responsiveInfo ? "100%" : "33%",
                                    display: "inline-block",
                                    margin: "1rem 0",
                                }}
                                key={key}
                            >
                                <h5
                                    style={{
                                        margin: 0,
                                        fontSize: "2vh",
                                        fontWeight: 700,
                                    }}
                                >
                                    {objDecocator[decoratorName]}
                                </h5>
                                <DynamicLink
                                    customStyle={{
                                        fontSize: responsiveInfo ? `3.2vh` : "2.3vh",
                                        fontWeight: 400,
                                        textDecoration: "underline",
                                        color: "#373a3c",
                                        width: "85%",
                                        display: "inline-block",
                                        whiteSpace: "nowrap",
                                        overflow: "hidden",
                                        textOverflow: "ellipsis",
                                    }}
                                    simpleLinkHref={`receitas/${data[item].slug}`}
                                    title={data[item].name}
                                />
                            </li>
                        );
                    })}
                </ul>
            </div>
        </>
    );
};

const NormalListPost = ({ searchFor, setData }) => {
    return (
        <>
            {searchFor.length === 0 ? (
                <>
                    <h4
                        style={{
                            ...styleTitleArea,
                            ...styleRecipeTitleMiddleArea,
                        }}
                    >
                        {" "}
                        Novas Dicas e Receitas do <strong>Dia a Dia</strong>{" "}
                    </h4>
                    <ListPosts data={setData} />
                </>
            ) : null}

            {searchFor.length < 4 && searchFor.length !== 0 ? (
                <h4 style={styleTitleArea}>
                    {" "}
                    Minimo de <strong>3 digitos</strong> para pesquisar por "{searchFor}"{" "}
                </h4>
            ) : null}
        </>
    );
};

const SearchListPosts = ({ searchFor, setData, searchUrl, searchTotalPages }) => {
    return (
        <>
            <h4 style={styleTitleAreaSearch}>
                Pesquisando por <strong>{searchFor.replace(/\+/g, " ")}</strong> ...
            </h4>

            {setData.length > 0 ? (
                <ListPosts search searchUrl={searchUrl} data={setData} totalPages={searchTotalPages} />
            ) : (
                <div style={styleAlertDanger}>
                    Desculpe! Nao temos nenhuma receita com a palavra:
                    <strong>{searchFor.replace(/\+/g, " ")}</strong>
                </div>
            )}
        </>
    );
};

I'm having the same problem with React Redux and nextjs build.

I'm having the same problem with React Redux and reactjs build.

If anyone has a repository they could share (does not have to be a private repo, it can just be a recreating of the issue in a separate/new repo) that would be super helpful. Otherwise it's a bit tough to piece together code snippets.

@jamesmosier if you send me a msg PVT
I could send to you the permission and the REPO.

I think that the solution will be general for all..
but I cant share the repo public.

@jamesmosier i added ur email from ur personal website to the repo
i hope this helps u to give us a solution

tks so much

Please create a public repository. It doesn't have to be the same repo, just a reproduction of the issue. That way others can help with this issue too and help to understand if this is a problem with Next or another library unrelated to Next.

@jamesmosier

here the public repo: https://github.com/cabralada/temp-repo-cmd

Was this page helpful?
0 / 5 - 0 ratings