Can't get the array state value in React - javascript

When I try to get value ...this.state.users shows error in react
React Code
handleChange(i, e) {
const { name, value } = e.target;
let users = [...this.state.users];
users[i] = { ...users[i], [name]: value };
this.setState({ users });
}
My webpack file
const path = require('path');
module.exports = (env) => {
const isProduction = env === 'production';
return {
entry: './src/index.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
},
module: {
rules: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/,
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
};
}
And the error is
ERROR in ./src/components/Index.js
[1] Module build failed: SyntaxError: E:/Program/reactjs/check/client/src/components/Index.js: Unexpected token (47:15)
Please help me to fix this error

It looks like you need to configure babel correctly.
According to this post, you need to make sure that you have the stage-0 preset installed:
npm install --save-dev babel-preset-stage-0
and configured:
{
"presets":[
"es2015", "react", "stage-0"
]
}
However, if you are using Babel v7 or higher you have to use a different installation & configuration:
npm install --save-dev #babel/plugin-proposal-object-rest-spread
and put it into your .babelrc file:
{
"plugins": ["#babel/plugin-proposal-object-rest-spread"]
}

Related

Building Gatsby components using Webpack cannot transpile Gatsby module

I am trying to make a library of Gatsby components (using specific Gatsby library rather than general React components).
I have been compiling using just babel but I want to be able to translate any CSS-in-JS and do other things so I am trying to build using Webpack.
When I try to compile the Gatsby component it fails in the Gatsby module. I know Gatsby is untranspiled ES6 so I included node_modules in my webpack configuration to transpile but I still:
ERROR in ./node_modules/gatsby/cache-dir/gatsby-browser-entry.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/kylecalica/Code/gatsby-learn/gatsby-components/node_modules/gatsby/cache-dir/gatsby-browser-entry.js: Unexpected token (25:4)
23 |
24 | return (
> 25 | <React.Fragment>
| ^
26 | {finalData && render(finalData)}
27 | {!finalData && <div>Loading (StaticQuery)</div>}
28 | </React.Fragment>
Webpack:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const htmlWebpackPlugin = new HtmlWebpackPlugin({
filename: "index.html"
});
module.exports = {
entry: path.join(__dirname, "/src/index.js"),
output: {
filename: 'main.js',
path: path.resolve(__dirname, "/webpack/dist")
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
]
},
plugins: [htmlWebpackPlugin],
devServer: {
contentBase: path.join(__dirname, "dist"),
port: 9000,
open: true
}
};
I am currently trying to take what Gatsby says to do to Storybook in my code but it's hard to figure out how to translate this from their strange way into mine?
Storybook's way of webpack:
module.exports = ({ config }) => {
// Transpile Gatsby module because Gatsby includes un-transpiled ES6 code.
config.module.rules[0].exclude = [/node_modules\/(?!(gatsby)\/)/]
// use installed babel-loader which is v8.0-beta (which is meant to work with #babel/core#7)
config.module.rules[0].use[0].loader = require.resolve("babel-loader")
// use #babel/preset-react for JSX and env (instead of staged presets)
config.module.rules[0].use[0].options.presets = [
require.resolve("#babel/preset-react"),
require.resolve("#babel/preset-env"),
]
config.module.rules[0].use[0].options.plugins = [
// use #babel/plugin-proposal-class-properties for class arrow functions
require.resolve("#babel/plugin-proposal-class-properties"),
// use babel-plugin-remove-graphql-queries to remove static queries from components when rendering in storybook
require.resolve("babel-plugin-remove-graphql-queries"),
]
// Prefer Gatsby ES6 entrypoint (module) over commonjs (main) entrypoint
config.resolve.mainFields = ["browser", "module", "main"]
return config
}
.babelrc :
{
"presets": [
"babel-preset-gatsby-package",
"#babel/preset-react",
"#babel/preset-env"
]
}
I solved this by converting what Storybook's webpack module had. I am still putting it through testing however but it compiles fine for now:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const htmlWebpackPlugin = new HtmlWebpackPlugin({
filename: "index.html"
});
module.exports = {
entry: path.join(__dirname, "/src/index.js"),
output: {
filename: 'index.js',
path: path.resolve(__dirname, "webpack")
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: "babel-loader",
options: {
presets: ["babel-preset-gatsby-package"],
plugins: ["#babel/plugin-proposal-class-properties"]
},
},
exclude: [/node_modules\/(?!(gatsby)\/)/],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
]
},
plugins: [htmlWebpackPlugin],
devServer: {
contentBase: path.join(__dirname, "dist"),
port: 9000,
open: true
}
};

Thumbnail component issue in react

I have added the thumbnail component into my project. I got to see the following error in my project after adding it. The error is shown in the following image.
Here's my webpack.config.js file code which might help you on understanding the issue. There's a loader to be specified there. I don't know what's the specified loader for this. Anyone faced the same issue?
Any help?
**/*webpack.config.js*/**
/* eslint comma-dangle: ["error",
{"functions": "never", "arrays": "only-multiline", "objects":
"only-multiline"} ] */
const webpack = require('webpack');
const pathLib = require('path');
const devBuild = process.env.NODE_ENV !== 'production';
const config = {
entry: [
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill',
'./app/bundles/HelloWorld/startup/registration',
],
output: {
filename: 'webpack-bundle.js',
path: pathLib.resolve(__dirname, '../app/assets/webpack'),
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new webpack.EnvironmentPlugin({ NODE_ENV: 'development' }),
],
module: {
rules: [
{
test: require.resolve('react'),
use: {
loader: 'imports-loader',
options: {
shim: 'es5-shim/es5-shim',
sham: 'es5-shim/es5-sham',
}
},
},
{
test: /\.jsx?$/,
use: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.css$/,
include: /node_modules/,
loaders: ['style-loader', 'css-loader'],
},
],
},
};
module.exports = config;
if (devBuild) {
console.log('Webpack dev build for Rails'); // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map';
} else {
console.log('Webpack production build for Rails'); // eslint-disable-line no-console
}
And Here's the code where I called the component:
import React, { Component } from 'react';
import Thumbnail from 'react-native-thumbnail-video';
class VideoThumnail extends Component {
render() {
return(
<div>
<Thumbnail url="https://www.youtube.com/watch?v=lgj3D5-jJ74" />
</div>
);
}
}
export default VideoThumnail;
You have a rule only for jsx. Try to add js extension in webpack also
{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/,
}
Also i see es6 synax, so try to add .babelrc in project root with this
{
"presets": ["stage-0"]
}
and install babel-preset-env (npm install --save babel-preset-env)

Dependency Not found even defined in package.json and node_modules

I use vue.js and vue-cli to create a project.
vue init webpack my-project
I am trying to create a component using http://photo-sphere-viewer.js.org/, thus I installed it using
npm install --save photo-sphere-viewer
Then it was downloaded in node_modules and appears in the package.json under dependencies as
"photo-sphere-viewer": "^3.2.3",
And I tried to import in a component, VR-Pano.vue, inside the script tag using
import PhotoSphereViewer from 'photo-sphere-viewer';
And
var PhotoSphereViewer = require('photo-sphere-viewer');
But when I run npm run dev
This dependency was not found:
photo-sphere-viewer in ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/components/VR-Pano.vue
I tried:
npm cache clean && npm update -g
Did some researches on webpack, but didn't really know what's going on as I am not too familiar with webpack. I was expecting it to be a simple process, but I suspect something isn't setup properly for my webpack or I did something very stupid.
Here is my webpack.base.conf.js
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
// target: 'electron-main',
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': resolve('src')
}
},
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('[path][name].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
}
I took this debugging opportunity to learn more about npm and webpack.
It looks like the creators of photo-sphere-viewer did not specify where their "main" file was, the file that gets returned when you import or require. I think by default npm looks for index.js at the project root. But a lot of times, package creators put their distribution files under a dist or lib directory. The photo-sphere people did this, but did not specify the location in their package.json. The solution is to add
"main":"./dist/photo-sphere-viewer.min.js"
to the photo-sphere-viewer package.json file. Make sure to add a trailing comma if you're not putting it at the very end. Also i would recommend filing an issue on their Github, this seems like a bug..
Alternatively, you can also do
import PhotoSphereViewer from 'photo-sphere-viewer/dist/photo-sphere-viewer.min.js';

Run Mocha specs from React app in a browser using Webpack and mocha-loader

I have a react App for which I'd like to run its mocha specs (unit-tests) in a browser. I found this SO post and tried to apply same idea to my project. I came up with the following webpack config file:
webpack.config.test.js
const nodeExternals = require('webpack-node-externals');
const path = require('path');
const host = 'localhost';
const port = '8084';
module.exports = {
target: 'web',
externals: [nodeExternals()],
entry: './specs/index.js',
output: {
filename: 'debug.bundle.js',
path: path.join(__dirname, 'tests'),
publicPath: `http://${host}:${port}/tests`,
},
devServer: {
host,
port,
},
module: {
rules: [
{
test: /\.js$/,
loaders: ['react-hot-loader', 'babel-loader'],
enforce: 'pre',
},
{
test: /.+Spec\.js$/,
loaders: ['mocha-loader'],
},
{
test: /(\.css|\.scss)$/,
loader: 'null-loader',
exclude: [
/build/,
],
},
{
test: /(\.jpg|\.jpeg|\.png|\.gif)$/,
loader: 'null-loader',
},
],
},
};
And, after starting the server with:
webpack-dev-server --config webpack.config.test.js
I get the following error in console:
I've read that the problem might be with webpack-node-externals but not really sure what's happening. Any ideas?
I think you will want to use webpack-node-externals only when you bundle files for backend (as described in plugin README). When you use it you forbid it to build all modules from node_modules folder.

no window object present webpack nodejs

I'm using webpack with babel to compile my ecmascript 6 code. Everything works fine but if I add certain dependeciens like the requests npm package. Here are my files:
main.js
import os from 'os'
export class User {
constructor(username) {
this.username = username;
}
register() {
console.log("registering...");
}
}
var client = new User("hey")
console.log(user.register());
webpack config:
var webpack = require('webpack')
module.exports = {
entry: [
'./src/main.js'
],
output: {
path: "dist",
publicPath: "/dist/",
filename: "stela.js"
},
watch: false,
module: {
loaders: [{
test: /\.js$/,
// excluding some local linked packages.
// for normal use cases only node_modules is needed.
exclude: /node_modules/,
loader: 'babel'
}, {
test: /\.json$/,
loader: 'json-loader'
}]
},
externals: {
fs: '{}',
tls: '{}',
net: '{}',
console: '{}'
},
babel: {
presets: ['es2015'],
plugins: ['transform-runtime']
},
resolve: {
modulesDirectories: ['node_modules']
}
}
Now if I run webpack and then run node dist/stella.js everything works fine it logs out registering...; however, if I add certain dependencies like the requests npm package:
...
import request from 'request'
...
I run webpack everything compiles down with no errors but then I try running node dist/stella.js and I get this error:
throw new Error('no window object present');
By default, Webpack is set up to target the browser, not a Node environment. Try setting target in your config:
module.exports = {
// ...
target: "node",
// ...
}

Categories