Need help to make [create-react-app] to use Aync - Await (transform-async-to-generator)! - reactjs

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

Related

Installation issue in tanstack react query dev tools

I am using #tanstack/react-query and I have installed the dev tools. After the installation when tried to start the server I get this error. What should be done ?
./node_modules/#tanstack/match-sorter-utils/build/umd/index.production.js 504:47
Module parse failed: Unexpected token (504:47)
File was processed with these loaders:
./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| return e.rank === n.rank ? 0 : e.rank > n.rank ? -1 : 1;
| }, e.rankItem = function (e, n, t) {
if ((t = t || {}).threshold = t.threshold ?? o.MATCHES, !t.accessors) {
| const r = s(e, n, t);
| return {

ReactJS: Fetch in bootstrap modal after an initial fetch

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.

how to check token in local storage without crashing in react.js

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.

Unexpected token RactJS

./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()

How to define a binding that accepts multiple types in the function signature using reason-react?

When defining a reason-react binding and I want to know how I can determine a binding that accepts multiple types. For example, I have an argument ~value that should accept: string, number, array(string) or array(number). At the moment I am using option('a) but I do not think this is the cleanest approach as I would prefer to define the type explicitly. How can this be done? I have looked at bs.unwrap but I am unsure how to combine external syntax into a function signature.
module Select = {
[#bs.module "material-ui/Select"] external reactClass : ReasonReact.reactClass = "default";
let make =
(
...
~menuProps: option(Js.t({..}))=?,
~value: option('a), /* Should be type to string, number, Array of string and Array of number */
~style: option(ReactDOMRe.style)=?,
...
children
) =>
ReasonReact.wrapJsForReason(
~reactClass,
~props=
Js.Nullable.(
{
...
"value": from_opt(value),
"style": from_opt(style)
}
),
children
);
};
As a side question, as number type is not defined in reason would my binding also have to map float and integer into numbers?
This is possible by using the following (inspired by https://github.com/astrada/reason-react-toolbox/).
type jsUnsafe;
external toJsUnsafe : 'a => jsUnsafe = "%identity";
let unwrapValue =
(r: [< | `Int(int) | `IntArray(array(int)) | `String(string) | `StringArray(array(string))]) =>
switch r {
| `String(s) => toJsUnsafe(s)
| `Int(i) => toJsUnsafe(i)
| `StringArray(a) => toJsUnsafe(a)
| `IntArray(a) => toJsUnsafe(a)
};
let optionMap = (fn, option) =>
switch option {
| Some(value) => Some(fn(value))
| None => None
};
module Select = {
[#bs.module "material-ui/Select"] external reactClass : ReasonReact.reactClass = "default";
let make =
(
...
~menuProps: option(Js.t({..}))=?,
~value:
option(
[ | `Int(int) | `IntArray(array(int)) | `String(string) | `StringArray(array(string))]
)=?,
~style: option(ReactDOMRe.style)=?,
...
children
) =>
ReasonReact.wrapJsForReason(
~reactClass,
~props=
Js.Nullable.(
{
...
"value": from_opt(optionMap(unwrapValue, value)),
"style": from_opt(style)
}
),
children
);
};
This can be used in the following way;
<Select value=(`IntArray([|10, 20|])) />
<Select value=(`Int(10)) />
I copied toJsUnsafe from reason-react-toolbox, so I'm not entirely sure exactly what it does, I will update my answer when I find out.
The unwrapValue function takes a value which can be one of the types listed and converts it to jsUnsafe.
The type for unwrapValue allows for any of variants listed, but also allows a subset of those, for example. (It's the < before the variants that enable this).
let option = (value: option([ | `String(string) | `Int(int)])) =>
Js.Nullable.from_opt(option_map(unwrapValue, value));
Just to add to #InsidersByte's answer, since this problem isn't reason-react-specific and can be generalized:
module Value = {
type t;
external int : int => t = "%identity";
external intArray : array(int) => t = "%identity";
external string : string => t = "%identity";
external stringArray : array(string) => t = "%identity";
};
let values : list(Value.t) = [
Value.int(4),
Value.stringArray([|"foo", "bar"|])
];
This solution is also self-contained inside the Value module, and incurs no overhead compared to the JavaScript equivalent since "%identity" externals are no-ops that are optimized away.

Resources