./src/index.js
Line 26: Parsing error: Unexpected token in reactjs.
My code,
fetch('https://www.reddit.com/r/reactjs.json')
.then((result) => {
// Get the result
// If we want text, call result.text()
return result.json();
}).then((jsonResult) => {
// Do something with the result
console.log(jsonResult);
})
}
I tired to run a code error will be show,
Failed to compile
./src/index.js
Line 26: Parsing error: Unexpected token
24 | }
25 |
> 26 | fetch('https://www.reddit.com/r/reactjs.json')
| ^
27 | .then((result) => {
28 | // Get the result
29 | // If we want text, call result.text()
Related
just tried to mocked the store then test the request with fetchMock but got this error :
you can check out the full repo on :
https://github.com/alibidjandy/layered-architecture
src/app/main/__tests__/main.test.tsx (5.569 s)
● Console
console.warn
Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.
7 | reducerPath: "productService",
8 | tagTypes: ["product"],
> 9 | baseQuery: fetchBaseQuery({
| ^
10 | baseUrl: serviceURL,
11 | }),
12 | endpoints: (builder) => ({}),
at fetchBaseQuery (node_modules/#reduxjs/toolkit/src/query/fetchBaseQuery.ts:180:13)
at Object.<anonymous> (src/app/main/data/api/service.ts:9:28)
at Object.<anonymous> (src/app/main/data/api/store.ts:3:1)
FAIL src/app/components/products/tests/products-requests.test.tsx
● Test suite failed to run
src/app/components/products/__tests__/products-requests.test.tsx:14:3 - error TS2304: Cannot find name 'fetchMock'.
14 fetchMock.resetMocks();
~~~~~~~~~
src/app/components/products/__tests__/products-requests.test.tsx:24:5 - error TS2304: Cannot find name 'fetchMock'.
24 fetchMock.mockResponse(JSON.stringify(dummyProducts));
~~~~~~~~~
src/app/components/products/__tests__/products-requests.test.tsx:41:5 - error TS2304: Cannot find name 'fetchMock'.
41 fetchMock.mockReject(new Error("Internal Server Error"));
~~~~~~~~~
src/app/components/products/__tests__/products-requests.test.tsx:61:5 - error TS2304: Cannot find name 'fetchMock'.
61 fetchMock.mockResponse(JSON.stringify(dummyProducts));
~~~~~~~~~
src/app/components/products/__tests__/products-requests.test.tsx:85:5 - error TS2304: Cannot find name 'fetchMock'.
85 fetchMock.mockReject(new Error("Internal Server Error"));
~~~~~~~~~
FAIL src/app/main/tests/service.test.ts (15.706 s)
● getProductById › request is correct
expect(jest.fn()).toBeCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
20 | .dispatch<any>(getProducts.initiate(undefined))
21 | .then(() => {
> 22 | expect(fetchMock).toBeCalledTimes(1);
| ^
23 | const { method, url } = fetchMock.mock.calls[0][0] as Request;
24 |
25 | expect(method).toBe("GET");
at src/app/main/__tests__/service.test.ts:22:27
● getProductById › unsuccessful response
TypeError: Cannot read property 'error' of undefined
51 | const {
52 | status,
> 53 | error: { error },
| ^
54 | isError,
55 | } = action;
56 | expect(status).toBe("rejected");
at src/app/main/__tests__/service.test.ts:53:20
● getProductById › request is correct
expect(jest.fn()).toBeCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
69 | .dispatch<any>(getProductById.initiate(dummyProduct.id))
70 | .then(() => {
> 71 | expect(fetchMock).toBeCalledTimes(1);
| ^
72 | const request = fetchMock.mock.calls[0][0] as Request;
73 | const { method, url } = request;
74 |
at src/app/main/__tests__/service.test.ts:71:27
● getProductById › unsuccessful response
TypeError: Cannot read property 'error' of undefined
102 | const {
103 | status,
> 104 | error: { error },
| ^
105 | isError,
106 | } = action;
107 | expect(status).toBe("rejected");
at src/app/main/__tests__/service.test.ts:104:20
Test Suites: 2 failed, 1 passed, 3 total
Tests: 4 failed, 3 passed, 7 total
Snapshots: 0 total
Time: 17.642 s
Ran all test suites.
install whatwg-fetch
after install it add import 'whatwg-fetch'; at the beginning (line 1) of the file.test youre using
The test in Jest doesn't run on the browser. It runs on NodeJS. So, you need a polyfill for the "fetch".
There are many options on NPM, but some of them haven't worked for me.
The one that worked fine was the cross-fetch: https://www.npmjs.com/package/cross-fetch
It works on browser/NodeJS/Mobile. You just need to add it to package.json (devDependencies) and import it on jest.setup.js file:
import 'cross-fetch/polyfill';
I have used fetch to render my database in a table, I was trying to use bootstrap modal to render an specific document and edit it to post again in database. I think these two calls to the server overcharge it, and then it can't render the components, I just want to make sure if there is another way to do make the second call. When I run this display the result is:
Unhandled Rejection (TypeError): Failed to fetch
callApi
5 | Accept: "application/json",
6 | };
7 |
8 | const response = await fetch("http://localhost:3002/api" + url, options);
| ^ 9 | const data = await response.json();
10 | return data;
11 |
View compiled
list
.../src/api.js:29
26 | },
27 | sales: {
28 | list() {
29 | return callApi("/sales")
| ^ 30 | },
31 | create(sale) {
32 | return callApi("/sales", {
View compiled
fetchData
.../src/screens/sales/SalesScreen.js:29
26 |
27 | useEffect(() => {
28 | const fetchData = async () => {
29 | const response = await api.sales.list();
| ^ 30 | setSales(response);
31 | console.log(sales);
32 | const responseUsers = await api.users.list();
View compiled
(anonymous function)
.../src/screens/sales/SalesScreen.js:37
34 | console.log(users);
35 | };
36 |
37 | fetchData();
| ^ 38 | }, []);
39 |
40 | return (
View compiled
▶ 11 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error. Click the 'X' or hit ESC to dismiss this message.
I am trying to convert the JavaScript sample code in ReactJS.
The compiler doesn't display any error but browser is throwing an error at runtime.
I am using this example, please see below.
https://codepen.io/kathykato/pen/prEmKe
I expect to see it workable as displays in above example but I am getting small errors.
What I have tried so far is given below
-------------------------Carousel.js--------------------------
import React, { useState, useEffect } from "react";
import './Carousel.scss'
const Carousel = () => {
const items = document.querySelectorAll('img');
const itemCount = items.length;
const nextItem = document.querySelector('.next');
const previousItem = document.querySelector('.previous');
let count = 0;
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
nextItem.addEventListener('click', showNextItem);
previousItem.addEventListener('click', showPreviousItem);
document.addEventListener('keydown', keyPress);
// clean up
return () => {
nextItem.removeEventListener('click', showNextItem);
previousItem.removeEventListener('click', showPreviousItem);
document.removeEventListener('keydown', keyPress);
};
})
function showNextItem() {
items[count].classList.remove('active');
if(count < itemCount - 1) {
count++;
} else {
count = 0;
}
items[count].classList.add('active');
console.log(count);
}
function showPreviousItem() {
items[count].classList.remove('active');
if(count > 0) {
count--;
} else {
count = itemCount - 1;
}
items[count].classList.add('active');
console.log(count);
}
function keyPress(e) {
e = e || window.event;
if (e.keyCode == '37') {
showPreviousItem();
} else if (e.keyCode == '39') {
showNextItem();
}
}
// nextItem.addEventListener('click', showNextItem);
// previousItem.addEventListener('click', showPreviousItem);
// document.addEventListener('keydown', keyPress);
return (
<div className="container">
<div className="slider">
<img className="active" src="https://source.unsplash.com/gKk9rpyDryU" alt="Nothing " />
<img src="https://source.unsplash.com/VFGEhLznjPU" alt="Nothing"/>
<img src="https://source.unsplash.com/InR-EhiO_js" alt="Nothing"/>
</div>
<nav className="slider-nav">
<ul>
<li className="arrow">
<button className="previous">
<span>
<i className="ion-arrow-left-c"></i>
</span>
</button>
</li>
<li className="arrow">
<button className="next">
<span>
<i className="ion-arrow-right-c"></i>
</span>
</button>
</li>
</ul>
</nav>
</div>
);
}
export default Carousel;
Application built with
{
"react": "16.13.0",
"react-dom": "^16.13.0",
"react-redux": "^7.2.0",
"redux": "^4.0.4"
"#material-ui/core": "^4.9.5"
}
Now see the errors below:
TypeError: Cannot read property 'addEventListener' of null
(anonymous function)
H:/ReactJs/Source Codes/react-master/react-master/src/components/Sliders/Carousel.js:14
11 |
12 | // Similar to componentDidMount and componentDidUpdate:
13 | useEffect(() => {
> 14 | nextItem.addEventListener('click', showNextItem);
| ^ 15 | previousItem.addEventListener('click', showPreviousItem);
16 | document.addEventListener('keydown', keyPress);
17 |
View compiled
commitHookEffectListMount
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:19731
19728 | if ((effect.tag & tag) === tag) {
19729 | // Mount
19730 | var create = effect.create;
> 19731 | effect.destroy = create();
| ^ 19732 |
19733 | {
19734 | var destroy = effect.destroy;
View compiled
commitPassiveHookEffects
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:19769
19766 | // before calling any create functions. The current approach only serializes
19767 | // these for a single fiber.
19768 | commitHookEffectListUnmount(Passive$1 | HasEffect, finishedWork);
> 19769 | commitHookEffectListMount(Passive$1 | HasEffect, finishedWork);
| ^ 19770 | break;
19771 | }
19772 | }
View compiled
HTMLUnknownElement.callCallback
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:188
185 | window.event = windowEvent;
186 | }
187 |
> 188 | func.apply(context, funcArgs);
| ^ 189 | didError = false;
190 | } // Create a global error event handler. We use this to capture the value
191 | // that was thrown. It's possible that this error handler will fire more
View compiled
invokeGuardedCallbackDev
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:237
234 | // errors, it will trigger our global error handler.
235 |
236 | evt.initEvent(evtType, false, false);
> 237 | fakeNode.dispatchEvent(evt);
| ^ 238 |
239 | if (windowEventDescriptor) {
240 | Object.defineProperty(window, 'event', windowEventDescriptor);
View compiled
invokeGuardedCallback
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:292
289 | function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
290 | hasError = false;
291 | caughtError = null;
> 292 | invokeGuardedCallbackImpl$1.apply(reporter, arguments);
293 | }
294 | /**
295 | * Same as invokeGuardedCallback, but instead of returning an error, it stores
View compiled
flushPassiveEffectsImpl
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:22853
22850 | while (_effect2 !== null) {
22851 | {
22852 | setCurrentFiber(_effect2);
> 22853 | invokeGuardedCallback(null, commitPassiveHookEffects, null, _effect2);
| ^ 22854 |
22855 | if (hasCaughtError()) {
22856 | if (!(_effect2 !== null)) {
View compiled
unstable_runWithPriority
H:/ReactJs/Source Codes/react-master/react-master/node_modules/scheduler/cjs/scheduler.development.js:653
650 | currentPriorityLevel = priorityLevel;
651 |
652 | try {
> 653 | return eventHandler();
| ^ 654 | } finally {
655 | currentPriorityLevel = previousPriorityLevel;
656 | }
View compiled
runWithPriority$1
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:11039
11036 |
11037 | function runWithPriority$1(reactPriorityLevel, fn) {
11038 | var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
> 11039 | return Scheduler_runWithPriority(priorityLevel, fn);
11040 | }
11041 | function scheduleCallback(reactPriorityLevel, callback, options) {
11042 | var priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel);
View compiled
flushPassiveEffects
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:22820
22817 | if (pendingPassiveEffectsRenderPriority !== NoPriority) {
22818 | var priorityLevel = pendingPassiveEffectsRenderPriority > NormalPriority ? NormalPriority : pendingPassiveEffectsRenderPriority;
22819 | pendingPassiveEffectsRenderPriority = NoPriority;
> 22820 | return runWithPriority$1(priorityLevel, flushPassiveEffectsImpl);
22821 | }
22822 | }
22823 |
View compiled
(anonymous function)
H:/ReactJs/Source Codes/react-master/react-master/node_modules/react-dom/cjs/react-dom.development.js:22699
22696 | if (!rootDoesHavePassiveEffects) {
22697 | rootDoesHavePassiveEffects = true;
22698 | scheduleCallback(NormalPriority, function () {
> 22699 | flushPassiveEffects();
| ^ 22700 | return null;
22701 | });
22702 | }
View compiled
workLoop
H:/ReactJs/Source Codes/react-master/node_modules/scheduler/cjs/scheduler.development.js:597
594 | currentPriorityLevel = currentTask.priorityLevel;
595 | var didUserCallbackTimeout = currentTask.expirationTime <= currentTime;
596 | markTaskRun(currentTask, currentTime);
> 597 | var continuationCallback = callback(didUserCallbackTimeout);
| ^ 598 | currentTime = exports.unstable_now();
599 |
600 | if (typeof continuationCallback === 'function') {
View compiled
flushWork
H:/ReactJs/Source Codes/react-master/node_modules/scheduler/cjs/scheduler.development.js:552
549 | try {
550 | if (enableProfiling) {
551 | try {
> 552 | return workLoop(hasTimeRemaining, initialTime);
| ^ 553 | } catch (error) {
554 | if (currentTask !== null) {
555 | var currentTime = exports.unstable_now();
View compiled
MessagePort.performWorkUntilDeadline
C:/ReactJs/Source Codes/react-master/node_modules/scheduler/cjs/scheduler.development.js:164
161 | var hasTimeRemaining = true;
162 |
163 | try {
> 164 | var hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime);
| ^ 165 |
166 | if (!hasMoreWork) {
167 | isMessageLoopRunning = false;
Thank you
First, you're using React so prefer using React handlers like the following :
const nextItem = document.querySelector('.next');
nextItem.addEventListener('click', showNextItem);
becomes :
<button className="next" onClick={showNextitem}>
<span>
<i className="ion-arrow-right-c"></i>
</span>
</button>
you need to read some articles about event handling in react.
useEffect needs an empty array as second param to work like componentDidMount.
useEffect(() => {
document.addEventListener('keydown', keyPress);
// clean up
return () => {
document.removeEventListener('keydown', keyPress);
};
},[])
then as Marc Charpentier has said you add onClick={functionName} to the html element.
The reason that you receive the error is that a functional component does not have lifecycle (unlike class component) and it runs line after line.
which means when this line
nextItem.addEventListener('click', showNextItem);
is executed, the component has not returned any html element and it's not rendered in DOM. it does not exist yet so it's null.
and as you can read from the error message Cannot read property 'addEventListener' of null it can not find addEventListener in null
If I run the first line of this code the app comes crashing down, I have been trying to do this simple thing and redirecting for hours.
const token = localStorage.getItem('usertoken') || '';
console.log('token', token);
if (token != undefined) {
console.log('a');
}
//error message
InvalidTokenError: Invalid token specified
./node_modules/jwt-decode/lib/index.js
D:/Code/bookreview/node_modules/jwt-decode/lib/index.js:9
__webpack_require__
D:/Code/bookreview/webpack/bootstrap:784
781 | };
782 |
783 | // Execute the module function
> 784 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 785 |
786 | // Flag the module as loaded
787 | module.l = true;
View compiled
fn
D:/Code/bookreview/webpack/bootstrap:150
147 | );
148 | hotCurrentParents = [];
149 | }
> 150 | return __webpack_require__(request);
| ^ 151 | };
152 | var ObjectFactory = function ObjectFactory(name) {
153 | return {
Edit: I was running this code in some other file without the if statement that was the problem. thanks
In the first line of your code, token is always being assigned a value, so token is never undefined. Since the default returned by getItem() is null you could change your code to be:
const token = localStorage.getItem('usertoken');
if (token) {
...
}
which will evaluate to true if token is not null, "", or some other falsy value.
I am new to [create-react-app] and I would like to find out how can I add : ["transform-async-to-generator"] to this build process? In regular cases I would add it in .babelrc, but does not look to work* with [create-react-app].
*By "does not look to work" - I see the following error.
Syntax error: ../web/src/App.js: Unexpected token, expected ( (17:13)
15 | }
16 |
> 17 | test = async () => {
| ^
18 | let x = await this.resolveAfter2Seconds();
19 | try{}
20 | catch(exception){
And is any way to extend [create-react-app], without modifying the package itself?
Thanks!
The problem is not with async functions. You should rewrite your code the next way:
// ...
test = async () => {
let x = await this.resolveAfter2Seconds();
// ...
}
or
// ...
async test(){
let x = await this.resolveAfter2Seconds();
// ...
}
You should add 2 plugins to babel: babel-plugin-transform-async-to-generator and babel-plugin-syntax-async-functions