Error "undefined is not an object" in React Native App [closed] - node.js

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am new working with React Native and Expo XDE, I am implementing the PropTypes in the file TaskList.js of type arrayOf but at the time of compiling the application I get an error indicating "undefined is not an object (evaluating 'react3.default.PropTypes.arrayOf ') "and even if I add another PropTypes of type String or another the same thing happens.
How can I solve this problem with the PropTypes?
Error
package.json
{
"name": "test",
"version": "0.1.0",
"private": true,
"devDependencies": {
"react-native-scripts": "1.11.1",
"jest-expo": "25.0.0",
"react-test-renderer": "16.2.0"
},
"main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
"scripts": {
"start": "react-native-scripts start",
"eject": "react-native-scripts eject",
"android": "react-native-scripts android",
"ios": "react-native-scripts ios",
"test": "node node_modules/jest/bin/jest.js"
},
"jest": {
"preset": "jest-expo"
},
"dependencies": {
"expo": "^25.0.0",
"react": "16.2.0",
"react-native": "0.52.0"
}
}
App.js
import React from 'react';
import { StyleSheet, Text, View, ListView } from 'react-native';
import TaskList from './TaskList';
export default class App extends React.Component {
constructor(props, context){
super(props, context);
this.state = {
todos:[
{
task : "Learn React Native"
},
{
task : "Learn Redux"
},
]
}
}
render() {
return (
<View style={styles.container}>
<TaskList todos={this.state.todos}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
TaskList.js
import React, {Component, PropTypes} from 'react';
import {View, Text, Button, ListView} from 'react-native';
class TaskList extends React.Component {
constructor(props, context){
super(props, context);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(props.todos),
}
}
renderRow =(todo)=>{
return(
<Text>{todo.task}</Text>
)
}
render(){
return(
<View>
<ListView
dataSource={this.state.dataSource}
key={this.props.todos}
renderRow={this.renderRow.bind(this)}
/>
</View>
)
}
}
TaskList.propTypes = {
todos: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
}
export default TaskList;

PropTypes were moved into their separate NPM package (v15+), prop-types and no longer exist on the React package. That's why it is reported as undefined. Install it and import:
import PropTypes from 'prop-types';

You need to add the dependency
npm install --save prop-types
This command install prop-types in your project. Check your package.json file in your project
"dependencies": {
"prop-types": "^15.6.1"
}
And import it on your project where you want to use. by importing following package
import PropTypes from 'prop-types'; // ES6

Related

Svelte/Typescript error : "unexpected token" during type declaration

So I have a Svelte application with TypeScript enabled but now I am having an issue for running it :
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
src\api.ts (4:7)
2:
3: export default class API {
4: url:string;
^
5:
I don't understand because the app was working before, and suddenly raised this error.
It seems that some versions related to TypeScript for Svelte was changed:
{
"name": "...",
"version": "...",
"private": ...,
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public --no-clear",
"validate": "svelte-check",
"check": "svelte-check --tsconfig ./tsconfig.json" /* + ADDED */
},
"devDependencies": {
"#rollup/plugin-commonjs": "...",
"#rollup/plugin-json": "...",
"#rollup/plugin-node-resolve": "^13.1.3",
"#rollup/plugin-typescript": "^8.0.0",
/* #smui/... stuffs */
"#tsconfig/svelte": "^2.0.0", /* ^1.0.0 -> ^2.0.0 */
"rollup": "^2.67.0",
"rollup-plugin-css-only": "^3.1.0",
"rollup-plugin-livereload": "^2.0.5",
"rollup-plugin-svelte": "^7.1.0",
"rollup-plugin-terser": "^7.0.2",
"svelte": "^3.46.3",
"svelte-check": "^2.0.0", /* ^1.0.0 -> ^2.0.0 */
"svelte-preprocess": "^4.0.0",
"tslib": "^2.0.0",
"typescript": "^4.0.0"
},
"dependencies": {
"sirv-cli": "^2.0.2",
"svelte-material-ui": "..."
}
}
/* Note: I replaced some unrelated properties/version by '...'. */
Of course executing npm install didn't help. And if I just remove the :string, it will throw the same error for all other :<type> in the code.
Note that the file is named .ts and that VSCode doesn't detect any syntax error in those files.
Config files (edit)
/* tsconfig.json */
{
"extends": "#tsconfig/svelte/tsconfig.json",
"include": ["src/**/*"],
"exclude": ["node_modules/*", "__sapper__/*", "public/*"]
}
/* rollup.config.js */
import svelte from 'rollup-plugin-svelte';
import commonjs from '#rollup/plugin-commonjs';
import json from '#rollup/plugin-json';
import resolve from '#rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import sveltePreprocess from 'svelte-preprocess';
import typescript from '#rollup/plugin-typescript';
import css from 'rollup-plugin-css-only';
const production = !process.env.ROLLUP_WATCH;
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
process.on('SIGTERM', toExit);
process.on('exit', toExit);
}
};
}
export default {
input: 'src/main.ts',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
svelte({
preprocess: sveltePreprocess({ sourceMap: !production }),
compilerOptions: {
dev: !production
}
}),
css({ output: 'bundle.css' }),
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
typescript({
sourceMap: !production,
inlineSources: !production
}),
json(),
!production && serve(),
!production && livereload('public'),
production && terser()
],
watch: {
clearScreen: false
}
};
No file svelte.config.js
So, I tried executing my app in a docker container, to see if it would work, and got a different error message, much more helpful:
[!] Error: Could not resolve './api.js' from src/App.js`
Indeed, the file is not named ./api.js but ./API.ts (forgot to change the import after renaming it to TS...)
So I changed the import like that:
/* Before (not working) */
import API from './api.js'
/* After (Good) */
import API from './API'
// NB. The filename is really in uppercase for me
TL;DR
Check your import for any import x from file.js which should be a TS file and replace them by import x from file (you should not write the .ts extension)
Explanation:
It is trying to import a JavaScript (.js) file, but find the TypeScript file (.ts) and import it instead (seems like it only cares about the "basename"), but without the TypeScript Support, creating this weird situation where it doesn't reconize TypeScript Syntax inside a .ts file.

`useTheme` must be used within `NativeBaseConfigProvider`

In my project I faced the above error can anyone tell me how to solve this error.
The error I faced is:
Error: useTheme must be used within NativeBaseConfigProvider
This error is located at:
in Container
in ProductContainer (created by App)
in RCTView (created by View)
in View (created by App)
in App (created by ExpoRoot)
in ExpoRoot
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
ProductContainer.js:
import React, { useState, useEffect } from 'react'
import { View, StyleSheet, ActivityIndicator, FlatList, Text} from 'react-native'
import { Container, Header, Icon, Item, Input } from 'native-base';
import ProductList from './ProductList';
import SearchedProduct from './SearchedProducts';
const data = require('../../assets/data/products.json');
const ProductContainer = () => {
const [products, setProducts ] = useState([]);
const [productsFiltered, setProductsFiltered] = useState([]);
const [focus, setFocus] = useState();
useEffect(() => {
setProducts(data);
setProductsFiltered(data);
setFocus(false);
return () => {
setProducts([])
setProductsFiltered([])
setFocus()
}
}, [])
const SearchProduct = (text) => {
setProductsFiltered(
products.filter((i) => i.name.toLowerCase().includes(text.toLowerCase()))
);
}
const openList = () => {
setFocus(true);
}
const onBlur = () => {
setFocus(flase);
}
return (
<Container>
<View style = {{ flexDirection: "row"}}>
<Input
width = "100%"
variant = "rounded"
placeholder="Search"
onFocus={openList}
onChangeText={(text) => SearchProduct(text)}
/>
</View>
{focus == true ? (
<SearchProduct
productsFiltered={productsFiltered}
/>
) : (
<View style={styles.container}>
<Text>Product Container</Text>
<View style={styles.listContainer}>
<FlatList
data={products}
numColumns={2}
renderItem={({item}) => <ProductList
key={item.brand}
item={item}/>}
keyExtractor={item => item.brand}
/>
</View>
</View>
)}
</Container>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default ProductContainer
App.js
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
//Screens
import Header from './Shared/Header'
import ProductContainer from './Screens/Products/ProductContainer'
export default function App() {
return (
<View style={styles.container}>
<Header />
<ProductContainer />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
package.json:
{
"name": "animal-feedmart",
"version": "1.0.0",
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject"
},
"dependencies": {
"expo": "~44.0.0",
"expo-status-bar": "~1.2.0",
"native-base": "^3.3.7",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-native": "0.64.3",
"react-native-base": "^1.1.0",
"react-native-safe-area-context": "^4.2.1",
"react-native-svg": "^12.3.0",
"react-native-web": "0.17.1"
},
"devDependencies": {
"#babel/core": "^7.12.9"
},
"private": true
}
Please can anyone help me solve this issue? Thanks in advance
in your app.js import NativeBaseProvider and wrap your other components with it
import { NativeBaseProvider } from 'native-base';
return (
<NativeBaseProvider>
{Your other components}
</NativeBaseProvider>
);
If you put in the native provider and it is still showing the error, please ensure to change your Header as native base removed it from v3 upward, use HStack instead and if you want to use the Header downgrade the native base version to v2.12.14
import { NativeBaseProvider } from 'native-base';
export default function App() {
return (
<NativeBaseProvider>
<View style={styles.container}>
<Header />
<ProductContainer />
<StatusBar style="auto" />
</View>
</NativeBaseProvider>
);
}
I have solved this in App.js
import { NavigationContainer } from '#react-navigation/native';
import { NativeBaseProvider, extendTheme } from 'native-base';
Create a Theme
const newColorTheme = {
brand: {
900: '#5B8DF6',
800: '#ffffff',
700: '#cccccc',
},
};
const theme = extendTheme({
colors: newColorTheme,
});
and use on
export default function App() {
return (
<NativeBaseProvider theme={theme}>
<NavigationContainer>
<Header />
<Main/>
</NavigationContainer>
</NativeBaseProvider>
);
}

PrivateRoute not redirecting in reactjs

I was building a website for developers following a Udemy course. It redirects users to the dashboard after they log in. I need to make the dashboard page private, so that only logged-in users can access it, therefore I put it in a private route. If a user signs out, I need to redirect the user to the sign in page using the privateroute function, however private route does not redirect it will stay on dashboard page, and when I type localhost://3000/dashboard I can access dashboard page without the user having to log in
I need your help to fix this
Thankyou in advance
dashboard components
import React from 'react';
import PropTypes from 'prop-types';
const Dashboard = props => {
return <div>Dashboard</div>;
};
Dashboard.propTypes = {};
export default Dashboard;
PrivateRoute components
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
const PrivateRoute = ({
component: Component,
auth: { isAuthenticated, loading },
...rest
}) => (
<Route
{...rest}
render={props =>
!isAuthenticated && !loading ? (
<Redirect to='/login' />
) : (
<Component {...props} />
)
}
/>
);
PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired,
};
const mapStateToProps = state => ({
auth: state.auth,
});
export default connect(mapStateToProps)(PrivateRoute);
App.js
import React, { Fragment, useEffect } from 'react';
import './App.css';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Landing from './components/layout/Landing';
import Login from './components/auth/Login';
import Register from './components/auth/Register';
import Alert from './components/layout/Alert';
// Redux
import { Provider } from 'react-redux';
import store from './store';
import { loadUser } from './actions/auth';
import setAuthToken from './utils/setAuthToken';
import Dashboard from './components/dashboard/Dashboard';
import PrivateRoute from './components/routing/PrivateRoute';
if (localStorage.token) {
setAuthToken(localStorage.token);
}
const App = () => {
useEffect(() => {
store.dispatch(loadUser());
}, []);
return (
<Provider store={store}>
<Router>
<Fragment>
<Navbar />
<Route exact path='/' component={Landing} />
<section className='container'>
<Alert />
<Switch>
<Route exact path='/register' component={Register} />
<Route exact path='/login' component={Login} />
<PrivateRoute exact path='/dashboard' component={Dashboard} />
</Switch>
</section>
</Fragment>
</Router>
</Provider>
);
};
export default App;
**auth.js **
import {
REGISTER_SUCCESS,
REGISTER_FAIL,
USER_LOADED,
AUTH_ERROR,
LOGIN_FAIL,
LOGIN_SUCCESS,
LOGOUT,
} from '../actions/types';
const initialState = {
token: localStorage.getItem('token'),
isAuthenticated: null,
loading: true,
user: null,
};
export default function (state = initialState, action) {
const { type, payload } = action;
switch (type) {
case USER_LOADED:
return {
...state,
isAuthenticated: true,
loading: false,
user: payload,
};
case REGISTER_SUCCESS:
case LOGIN_SUCCESS:
localStorage.setItem('token', payload.token);
return {
...state,
...payload,
isAuthenticated: true,
loading: false,
};
case REGISTER_FAIL:
case AUTH_ERROR:
case LOGIN_FAIL:
case LOGOUT:
localStorage.removeItem('token');
return {
...state,
token: null,
isAuthenticated: false,
loading: false,
};
default:
return state;
}
}
package.json in client side
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^12.1.2",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.24.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^6.0.0",
"react-router-dom": "^4.3.1",
"react-scripts": "5.0.0",
"redux": "^4.1.2",
"redux-devtools-extension": "^2.13.9",
"redux-thunk": "^2.4.1",
"uuid": "^8.3.2",
"web-vitals": "^2.1.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:5000"
}
It was a loading issue. The loading value does not change. The value remained true,
Therefore, I removed the loading check from the render. This worked.
const PrivateRoute = ({
component: Component,
auth: { isAuthenticated },
...rest
}) => (
<Route
{...rest}
render={props =>
!isAuthenticated ? (
<Redirect to='/login' />
) : (
<Component {...props} />
)
}
/>
);

TypeError: Cannot read property 'getters' of undefined when serving on Vuex 4 and Vue 3

I am new to Vuex and I have problem. I cannot serve my app properly using npm run serve. I can open the app on localhost but it display nothing, just html body with styled background color. Previously I do npm run build
F:\Javascript\CodeHighlighter>npm run build
> code-highlighter#0.1.0 build F:\Javascript\CodeHighlighter
> vue-cli-service build
- Building for production...
DONE Compiled successfully in 6447ms 08:44:40
File Size Gzipped
dist\js\chunk-vendors.74c072d0.js 120.47 KiB 42.78 KiB
dist\js\app.f18138cd.js 5.18 KiB 2.08 KiB
dist\css\app.60b393b9.css 1.78 KiB 0.65 KiB
Images and other types of assets omitted.
DONE Build complete. The dist directory is ready to be deployed.
INFO Check out deployment instructions at https://cli.vuejs.org/guide/deployment.html
Then I do npm run serve
F:\Javascript\CodeHighlighter>npm run serve
> code-highlighter#0.1.0 serve F:\Javascript\CodeHighlighter
> vue-cli-service serve
INFO Starting development server...
98% after emitting CopyPlugin
DONE Compiled successfully in 4139ms 08:45:52
App running at:
- Local: http://localhost:8080/
- Network: http://192.168.0.116:8080/
Note that the development build is not optimized.
To create a production build, run npm run build
when I open http://localhost:8080/ and open console. There is 1 error and 2 warning.
[Vue warn]: Property "$store" was accessed during render but is not defined on instance.
at <Header>
at <App>
[Vue warn]: Unhandled error during execution of render function
at <Header>
at <App>
Uncaught TypeError: Cannot read property 'getters' of undefined
There is my directory
And there is my full code
main.js
import { createApp } from 'vue'
import { createStore } from 'vuex'
import { store } from './store/store'
import App from './App.vue'
// console.log(store);
const app = createApp(App).mount('#app');
const vuestore = createStore(store);
app.use(vuestore);
store.js
import Vuex from 'vuex';
export const store = new Vuex.Store({
strict:true,
state:{
title: 'Code Highlighter',
copyright:{
license : 'MIT',
author : 'Philip Purwoko',
repository : 'https://github.com/PhilipPurwoko/CodeHighlighter'
},
api: "https://highlight-code-api.jefrydco.vercel.app/api",
langs: ["javascript", "python"]
},
getters:{
getTitle:state=>{
return state.title;
},
getCopyright:state=>{
return state.copyright;
},
getAPI:state=>{
return state.api;
},
getLangs:state=>{
return state.langs;
}
}
});
App.vue
<template>
<main>
<app-header></app-header>
<code-block></code-block>
<app-footer></app-footer>
</main>
</template>
<script>
import Header from "./components/Header.vue";
import Footer from "./components/Footer.vue";
import CodeBlock from "./components/CodeBlock.vue";
export default {
components: {
"app-header": Header,
"code-block": CodeBlock,
"app-footer": Footer,
},
};
</script>
CodeBlock.vue
<template>
<div>
<form>
<strong class="monospace">Select Language</strong>
<select v-model="lang" #change="highlight">
<option selected disabled>Choose Language</option>
<option v-bind:key="lan" v-for="lan in getLangs">{{ lan }}</option>
</select>
</form>
<section class="code-container">
<textarea class="code-block" v-model="code" #input="highlight" ></textarea>
<div class="code-block formated" v-html="formated"></div>
</section>
</div>
</template>
<script>
import axios from "axios";
import { mapGetters } from 'vuex';
export default {
data: function() {
return {
lang: "",
code: "",
formated: ""
};
},
computed:{
...mapGetters([
'getAPI',
'getLangs',
'getFormated',
'getCode'
])
},
methods: {
highlight() {
if (this.code == "") {
this.code = " ";
}
if (this.lang != "") {
axios
.post(
this.getAPI + `?lang=${this.lang}`,
{
code: this.code
}
)
.then(res => {
this.formated = res.data.data;
});
} else {
this.formated = "<p class='monospace' style='color:azure;'>No language selected. Please select a language</p>";
}
}
}
};
</script>
package.json
{
"name": "code-highlighter",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.20.0",
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vuex": "^4.0.0-beta.4"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0-0"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
You can also access my github repository at here (https://github.com/PhilipPurwoko/CodeHighlighter/tree/restart). I really appreciate for all of your responses. Thank you
First, please read the Vuex documentation for Vue 3. I've found the mistake you've made that you should use the Vue plugin before mounting the Vue Instance. It's should look like this. Good luck!
import { createApp } from 'vue'
import { store } from './store'
import App from './App.vue'
// Create vue instance
const app = createApp(App);
// Install the plugin first
app.use(store);
// Mount your app
app.mount('#app');

axios.post doesn't seem to work?

Maybe I am just not using axios correctly but I currently have a react front-end and node.js back end.
I am trying to POST to my api endpoint "/api/:id/addItem" but nothing is logging when making the request.
Here is my code:
ListForm component ->
import React from 'react';
import * as helpers from '../helpers';
class ListForm extends React.Component {
state = {
value: ''
}
handSubmit = e => {
e.preventDefault();
helpers.addItem(this.props.currentUser.googleId, this.state.value);
this.setState({value: ''});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text"
value={this.state.value}
onChange={e => this.setState({value: e.target.value})}
/>
<button>Add item</button>
</form>
);
}
}
export default ListForm;
Routes ->
const mongoose = require('mongoose');
const User = require('../models/userSchema');
module.exports = (app) => {
app.post('/api/:id/addItem', (req, res) => {
console.log('HEY!');
});
};
helpers.js ->
import axios from 'axios';
export const fetchUser = async () => {
const resp = await axios.get('/api/current_user');
return resp.data;
}
export const addItem = async (id, newItem) => {
const resp = await axios.post("/api/" + id + "/addItem", newItem);
return resp.data;
}
Package.json to show forwarding requests->
{
"name": "client",
"version": "0.1.0",
"private": true,
"proxy": {
"/auth/google": {
"target": "http://localhost:5000"
},
"/api/*": {
"target": "http://localhost:5000"
}
},
"dependencies": {
"axios": "^0.17.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-scripts": "1.0.17"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
Issue here is with newItem , its not json it's just simple value
axios.post("/api/" + id + "/addItem", newItem);
It should be like :
axios.post("/api/" + id + "/addItem", {value : newItem});
Or pass json from addItem :
helpers.addItem(this.props.currentUser.googleId, this_should_be_json );

Resources