React Unexpected Token with Async - reactjs

I am trying to define a function as you see below.
const fetchRoles = async () => {
const fetchedRoles = await axiosInstance.get('/roles/');
setRoles(fetchedRoles.data)
}
And I am getting error "Unexpected token () ^=>".
Why I am getting this error ?
I am using node version v12.18.2 and npm version 6.14.7
Thanks..

I solved the problem.
For their person who may experience this problem,
This error comes from eslint-loader. So I updated eslint config with ecmaVersio 8 and problem solved.
My parser conf,
"parserOptions": {
"ecmaVersion": 8,
"sourceType": "module",
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
}
}

Related

Prettier, React Router 6, useParams hook, unexpected token

I've been smashing my face into this problem the entire morning.
I recently assembled a new project with React 18, React Router 6, TypeScript, Webpack 5, eslint, and prettier.
Things were going fine until I tried out the useParams hook, and now my linter keeps printing out the following error:
/.../index.tsx
9:41 error Parsing error: Unexpected token prettier/prettier
✖ 1 problem (1 error, 0 warnings)
I have been searching around on Google, but I have not found anything talking about this issue directly. I'm not sure what to do at this point other than remove prettier from the project.
Here's my eslintrc:
{
"root": true,
"parser": "#typescript-eslint/parser",
"plugins": [
"react",
"#typescript-eslint",
"prettier"
],
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:#typescript-eslint/recommended",
"plugin:prettier/recommended"
],
"settings": {
"import/resolver": {
"alias": [
["components", "./src/components"],
["routes", "./src/routes"],
["views", "./src/views"]
]
},
"react": {
"version": "detect"
}
},
"env": {
"browser": true,
"es2021": true,
"node": true
}
}
Prettier config:
{
"arrowParens": "avoid",
"bracketSpacing": true,
"htmlWhitespaceSensitivity": "css",
"insertPragma": false,
"bracketSameLine": false,
"jsxSingleQuote": true,
"parser": "babel",
"printWidth": 80,
"proseWrap": "preserve",
"requirePragma": false,
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"endOfLine": "auto",
"useTabs": false
}
and the offending page:
import React from 'react';
import { useParams } from 'react-router-dom';
type ParamTypes = {
id: string
};
const Customer: React.FC = () => {
const { id } = useParams<ParamTypes>();
return <div>{id}</div>;
};
export default Customer;
According to Prettier, the offending character is the final parenthesis:
const { id } = useParams<ParamTypes>();
^
I figured it out.
The issue was in my prettier config: "parser": "babel". According to the docs, this does not need to be set, since Prettier can infer which parser it needs to use based on the file.
Removing this setting has briefly restored my sanity. Hooray.
Mystery solved.

CRA unable to build due to eslint import/no-webpack-loader-syntax

I am unable to build my Create-React-App due to Unexpected '!' in 'worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker'. Do not use import syntax to configure webpack loaders import/no-webpack-loader-syntax. I want to know why does it happen and how can I fix it?
I am building a React project with React Map GL. Due to the transpiling issue of Mapbox GL version 2.0+ (related here: https://github.com/mapbox/mapbox-gl-js/issues/10173), one of the workarounds suggests that adding a worker-loader to the project.
However, even using the eslint-disable-next-line comment, I am still getting the build error.
Here is the code snipet where I am using the worker-loader
import mapboxgl from 'mapbox-gl';
// eslint-disable-next-line import/no-webpack-loader-syntax
mapboxgl.workerClass =
require('worker-loader!mapbox-gl/dist/mapbox-gl-csp-worker').default;
Here is my eslint config file:
{
"env": {
"browser": true
},
"extends": [
],
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 2020,
"sourceType": "module"
},
"plugins": ["react-hooks", "react", "import"],
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
"linebreak-style": ["error", "windows"],
"react/prop-types": 0,
"import/no-webpack-loader-syntax": "off"
}
}

eslint vscode plugin is not producing warnings for hooks

I created a react app with npx create-react-app my-app and did a yarn install. Added the following to App.js:
const a = () => 1,
b = () => 2,
c = () => 3;
function App() {
const wut = useMemo(() => {
return { a: a(), b: b(), c: c() };
}, [a]);
useEffect(() => {
console.log(a(), b(), c());
}, [a]);
Yarn start will give me warnings but vscode does not.
I added .eslintrc.js with the following content:
module.exports = {
env: {
browser: true,
es6: true
},
extends: ["eslint:recommended", "plugin:react/recommended"],
globals: {
Atomics: "readonly",
SharedArrayBuffer: "readonly"
},
parserOptions: {
ecmaFeatures: {
jsx: true
},
ecmaVersion: 2018,
sourceType: "module"
},
plugins: ["react"],
rules: {
"react/prop-types": [0],
"no-console": [0],
"react-hooks/exhaustive-deps": "warn"
}
};
The list of rules for react/recommended doesn't include react-hooks/exhaustive-deps.
You likely didn't install eslint-plugin-react-hooks.
It includes a note:
Note: If you're using Create React App, please wait for a corresponding release of react-scripts that includes this rule instead of adding it directly.
What version of c-r-a are you using? In theory it was added via this PR.
I'm using TypeScript, so the answer for me was to add the following to my VSCode settings:
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
],
If I have the following code in a clean create-react-app:
function App(props) {
const {a,b,c}=props;
const wut = useMemo(() => {
console.log("this should not happen multiple times");
return { a: a(), b: b(), c: c() };
}, [a]);
useEffect(() => {
console.log(a(), b(), c());
}, [a]);
Then removing the .eslintrc.js would give me the React Hook useMemo has missing dependencies: warning and the option to auto fix it.
When I have the .eslintrc.js in project root directory I get the error Definition for rule 'react-hooks/exhaustive-deps' was not found. this is because the .eslintrc.js was missing a plugin and plugins: ["react", "react-hooks"], solved it.
However; now the rule is off by default so it won't warn, needed to explicitly add the rule and set it to warn (or error) in the .eslintrc.js:
rules: {
"react-hooks/exhaustive-deps": "error"
}

eslint Parsing error: Unexpected token up in migration.js

in my previous project i used this syntax for migration to mongoDB:
my_migration.js //
'use strict';
import slug from 'slugify';
module.exports = {
async up(db) {
const categories = [
{
title: 'football',
slug: slug('football'),
createdAt: new Date().getTime(),
updatedAt: new Date().getTime()
},
];
await db.collection('categories').insertMany(categories);
}
};
And it works, but an another project(Nextjs, Reactjs, Nodejs) I have eslint error:
[eslint] Parsing error: Unexpected token up
(method) up(db: any): Promise<void>
What I am doing incorrect? Thanks for any help.
eslintrc.js/
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"ecmaVersion": 2017,
"sourceType": "module"
},

ESLintError in plugin 'gulp-eslint' - Parsing error: Unexpected token

I'm working on a ReactJs project, I am writing code with ES7 in order to write more elegant code inside my React component, specifically static propTypes.
I use Gulp with Babel, ESlint, but I cannot fix a compilation error related to my static propTypes
This is the error message I get
[11:12:34] ESLintError in plugin 'gulp-eslint'
Message:
Parsing error: Unexpected token =
Details:
fileName: [MYFOLDER]/client/components/app/article/asset/index.js
lineNumber: 5
[11:12:36]
[MYFOLDER]/client/components/app/article/asset/index.js
5:19 error Parsing error: Unexpected token =
and it is referred to the line static propTypes = {
import React from 'react';
export default class Asset extends React.Component {
static propTypes = {
articleImageUrl: React.PropTypes.string.isRequired,
};
static defaultProps = {
articleImageUrl: 'https://placeholdit.imgix.net/~text?txtsize=60&txt=640%C3%97480&w=640&h=480'
};
constructor(props) {
super(props);
}
render() {
return (
<div className="article__asset">
<figure>
<img src={this.props.articleImageUrl} />
</figure>
</div>
);
}
}
This is my babel configuration
return browserify({
debug: true,
entries: [`${NPM_DIR}/es5-shim/es5-shim.js`, CLIENT_DIR + '/index.js']
})
.transform(babelify.configure({
sourceMapRelative: CLIENT_DIR,
presets: ['react', 'es2015', 'stage-0'],
plugins: ["transform-object-rest-spread", "transform-decorators-legacy", "transform-class-properties"]
}))
.bundle()
.on('error', function(e){
gutil.log(e);
})
.pipe(source('bundle.js'))
.pipe(rename('bundle.min.js'))
.pipe(gulp.dest(PUBLIC_DIR));
This is my eslint configuration
{
"plugins": [
"react"
],
"extends": ["eslint:recommended", "plugin:react/recommended"],
"ecmaVersion": 7,
"rules": {
// rules
},
"parserOptions": {
"sourceType": "module",
"ecmaFeatures": {
"jsx": true,
"blockBindings": true
}
}
}
What am I doing wrong? Thanks a lot
Use the babel-eslint parser in your ESLint configuration.
npm install babel-eslint --save
{
"parser": "babel-eslint",
"plugins": ["react"],
...
}

Resources