DEV Community

Christopher McClister
Christopher McClister

Posted on

"SyntaxError: Cannot use import statement outside a module" error with createContext and useReducer

Hi,

I am getting the following error when trying to create a Context Provider file:

\src\helpers\GlobalContextProvider.js:1
import React from 'react';
^^^^^^
SyntaxError: Cannot use import statement outside a module

My installation of React is recent, I've confirmed that my version of Typescript is updated, tsconfig.json is set up for ES6, and all of the other things that a web search suggests when encountering this issue. I'm hoping someone here can help to understand what I am doing wrong. I've included the code below. I believe it is a simple, standard set up, based upon tutorials and code examples that I've seen. FYI, I was originally using "import" for createContext and useReducer, but doing so produced the same error above for them as well. Any help with this would be greatly appreciated. Thank you!

The code for GlobalContextProvider.js:

import React from 'react';
const createContext = require('react');
const useReducer = require('react');

const GlobalStateContext = createContext({});
const GlobalDispatchContext = createContext({});

const initialState = {
dbConfig: {},
dbQuery: ""
};

const reducer = (state, action) => {
switch (action.type) {
case 'SET_CONFIG_OBJECT': {
return {
...state,
dbConfig: state.dbConfig,
};
}
case 'SET_QUERY_STATE': {
return {
...state,
dbQuery: state.dbQuery,
};
}
default:
throw new Error('Bad Action Type');
}
};

const GlobalContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
return (


{children}


);
};

module.exports = {
GlobalContextProvider
}

Top comments (0)