0

I am having the following code that gives me an error "SyntaxError: Cannot use import statement outside a module" and it points to the first row of the file: import React, {createContext} from 'react';

import React, {createContext} from 'react';

const UserContext = React.createContext({
   isLoggedIn: false,
   UID: '',
   setUID: () => {},
   login: () => {},
   logout: () => {}
});

export default UserContext;

I have tried to add "type": "module" to my package.json but it causes a new error "ReferenceError: require is not defined" that points to my app.js file to the row "const express = require('express')". I have also tried to change the file name from UserContext.js to UserContext.mjs but it didn't solve the problem. What can I do to fix this problem?

Developer
  • 7
  • 4
  • 1
    Use this `import {React, createContext} from 'react';` – Beshambher Chaukhwan Apr 03 '21 at 14:20
  • I tried this but it gives me the same error – Developer Apr 03 '21 at 14:27
  • This should seal the deal import * as React from 'react' const UserContext = React.createContext({ isLoggedIn: false, UID: '', setUID: () => {}, login: () => {}, logout: () => {} }); export default UserContext; – Kamran Apr 03 '21 at 14:28
  • This didn't work either, the problem seems to be the word "import" but I don't understand why because every other files that I have, have this kind of import React and they work well – Developer Apr 03 '21 at 14:31
  • Can you make a replica of any other working file and put your code underneath the import statement. Try it that way then – Kamran Apr 03 '21 at 14:32
  • I have read that discussion and tried those things but nothing worked :( – Developer Apr 03 '21 at 15:04
  • You have already imported createContext, so no need to write React. createContext. Simply write const UserContext = createContext({ .. }); – DIPANKAR BARMAN Apr 03 '21 at 16:05
  • I tried that now but then I get the error Unexpected token 'export' and it points to the last row "export default UserContext;" – Developer Apr 04 '21 at 08:12

0 Answers0