React is taking setstate as a function - javascript

I am using Machine Learning Face Detection API from a website called "clarifai", Though in my react App.js folder there is an issue, and the error says, "TypeError: this.setstate is not a function ". I am attaching a link to an image of my React localhost.React localhost screenshot
Actually, I am a beginner in react and trying to build a basic react website and embedding Machine learning API to detect faces when a user tries to enter an image link. Any help would be much appreciated !
import React, { Component } from 'react';
import Navigation from './Components/Navigation/Navigation';
import FaceRecognition from './Components/FaceRecognition/FaceRecognition';
import Clarifai from 'clarifai';
import Logo from './Components/Logo/Logo';
import ImageLinkForm from './Components/ImageLinkForm/ImageLinkForm';
import Rank from './Components/Rank/Rank';
import Particles from 'react-particles-js';
import './App.css';
const app = new Clarifai.App({
apiKey: 'API_KEY'
});
const particlesOptions = {
particles: {
number: {
value:100,
density: {
enable: true,
value_area:800
}
}
}
}
class App extends Component {
constructor() {
super();
this.state = {
input:'',
imageUrl:'',
box: {},
}
}
calculateFaceLocation = (data) =>{
const clarifaiFace = data.outputs[0].data.regions[0].region_info.bounding_box
const image = document.getElementById('inputimage');
const width = Number(image.width);
const height = Number(image.height);
return{
leftCol: clarifaiFace.left_col * width,
topRow : clarifaiFace.top_row * height,
rightCol : width - (clarifaiFace.right_col * width),
bottomRow : height - (clarifaiFace.bottom_row * height)
}
}
displayFaceBox = (box) => {
console.log(box);
this.setState = ({box: box})
}
onInputChange = (event) => {
this.setState({input: event.target.value});
}
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input});
app.models
.predict(Clarifai.FACE_DETECT_MODEL,
this.state.input)
.then(response => this.displayFaceBox(this.calculateFaceLocation(response)))
.catch(err => console.log(err));
}
render() {
return (
<div className="App">
<Particles className='particles'
params={particlesOptions}
/>
<Navigation />
<Logo />
<Rank />
<ImageLinkForm
onInputChange={this.onInputChange}
onButtonSubmit={this.onButtonSubmit}/>
<FaceRecognition box={this.state.box} imageUrl={this.state.imageUrl}/>
</div>
);
}
}
export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Call the setState function, don't change its definition
displayFaceBox = (box) => {
console.log(box);
// you can also use object short hand, instead of {box: box}
this.setState({box});
}

Make following changes in your code and see if it works.
Change
this.setState = ({box: box})
To
this.setState({box})

Related

Importing React Autosuggest as Functional Component from Another JSX File

I'm currently making a simple web frontend with react using react-autosuggest to search a specified user from a list. I want to try and use the Autosuggest to give suggestion when the user's type in the query in the search field; the suggestion will be based on username of github profiles taken from github user API.
What I want to do is to separate the AutoSuggest.jsx and then import it into Main.jsx then render the Main.jsx in App.js, however it keeps giving me 'TypeError: _ref2 is undefined' and always refer to my onChange function of AutoSuggest.jsx as the problem.
Below is my App.js code:
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Header from './views/header/Header';
import Main from './views/main/Main';
import Footer from './views/footer/Footer';
const App = () => {
return (
<>
<Header/>
<Main/> <- the autosuggest is imported in here
<Footer/>
</>
);
}
export default App;
Below is my Main.jsx code:
import React, { useState } from 'react';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import axios from 'axios';
import { useEffect } from 'react';
import AutoSuggest from '../../components/AutoSuggest';
const Main = () => {
const [userList, setUserList] = useState([]);
useEffect(() => {
axios.get('https://api.github.com/users?per_page=100')
.then((res) => setUserList(res.data))
.catch((err) => console.log(err));
}, [])
return (
<Container>
<br/>
<Row>
<AutoSuggest userList={userList} placeHolderText={'wow'} />
</Row>
</Container>
);
}
export default Main;
Below is my AutoSuggest.jsx code:
import React, { useState } from "react";
import Autosuggest from 'react-autosuggest';
function escapeRegexCharacters(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function getSuggestions(value, userList) {
const escapedValue = escapeRegexCharacters(value.trim());
if (escapedValue === '') {
return [];
}
const regex = new RegExp('^' + escapedValue, 'i');
return userList.filter(user => regex.test(user.login));
}
function getSuggestionValue(suggestion) {
return suggestion.name;
}
function renderSuggestion(suggestion) {
return (
<span>{suggestion.name}</span>
);
}
const AutoSuggest = ({userList, placeHolderText}) => {
const [value, setValue] = useState('');
const [suggestions, setSuggestions] = useState([]);
const onChange = (event, { newValue, method }) => { <- error from console always refer here, I'm not quite sure how to handle it..
setValue(newValue);
};
const onSuggestionsFetchRequested = ({ value }) => {
setValue(getSuggestions(value, userList))
};
const onSuggestionsClearRequested = () => {
setSuggestions([]);
};
const inputProps = {
placeholder: placeHolderText,
value,
onChange: () => onChange()
};
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={() => onSuggestionsFetchRequested()}
onSuggestionsClearRequested={() => onSuggestionsClearRequested()}
getSuggestionValue={() => getSuggestionValue()}
renderSuggestion={() => renderSuggestion()}
inputProps={inputProps} />
);
}
export default AutoSuggest;
The error on browser (Firefox) console:
I have no idea what does the error mean or how it happened and therefore unable to do any workaround.. I also want to ask if what I do here is already considered a good practice or not and maybe some inputs on what I can improve as well to make my code cleaner and web faster. Any input is highly appreciated, thank you in advance!
you have to write it like this... do not use the arrow function in inputProps
onChange: onChange

./node_modules/axios/lib/helpers/cookies.js Error: EPERM: operation not permitted, read

I'm trying to simply use an api but it's giving me this error. I've tried all possible solutions out there still nothing.
im running this as admin and it's windows 10
firewall antivirus is off
tired uninstalling and installing npm
tried npm cache clean --force command too
tired deselecting read-only if node_modules property.
import React, { Component } from "react";
import Clarifai from "clarifai";
import ImageSearchForm from "./components/ImageSearchForm/ImageSearchForm";
import FaceDetect from "./components/FaceDetect/FaceDetect";
import "./App.css";
// You need to add your own API key here from Clarifai.
const app = new Clarifai.App({
apiKey: "My api xxx",
});
class App extends Component {
constructor() {
super();
this.state = {
input: "",
imageUrl: "",
box: {},
};
}
calculateFaceLocation = (data) => {
const clarifaiFace =
data.outputs[0].data.regions[0].region_info.bounding_box;
const image = document.getElementById("inputimage");
const width = Number(image.width);
const height = Number(image.height);
return {
leftCol: clarifaiFace.left_col * width,
topRow: clarifaiFace.top_row * height,
rightCol: width - clarifaiFace.right_col * width,
bottomRow: height - clarifaiFace.bottom_row * height,
};
};
displayFaceBox = (box) => {
this.setState({ box: box });
};
onInputChange = (event) => {
this.setState({ input: event.target.value });
};
onSubmit = () => {
this.setState({ imageUrl: this.state.input });
app.models
.predict(Clarifai.FACE_DETECT_MODEL, this.state.input)
.then((response) =>
this.displayFaceBox(this.calculateFaceLocation(response))
)
.catch((err) => console.log(err));
};
render() {
return (
<div className="App">
<ImageSearchForm
onInputChange={this.onInputChange}
onSubmit={this.onSubmit}
/>
<FaceDetect box={this.state.box} imageUrl={this.state.imageUrl} />
</div>
);
}
}
export default App;

React Native state not resetting properly on navigating between screens

I am trying to implement the following case with two screens:
Adding players screen
Game screen: Challenges are read from JSON file and filled in with random variables during runtime. Example: in "p(1) drinks sips(2,4)" p(1) will be replaced with a random choice of a list of players, and sips will be replaced by either 2, 3 or 4 sips.
I am using stack navigation, passing the result of adding players in the player screen to the challenge screen. It works perfectly fine when I first start the game, but when I pop screen 2, and go back to screen 2, the challenges appear in random order (as expected), but they are already filled in.
The initialstate reads the non-filled in challenges from a JSON file, so why are the challenges already filled in when I rerender screen 2.
Gamescreen:
import React, { useState } from 'react';
import { StyleSheet, View, Text, TouchableWithoutFeedback, Alert } from 'react-native';
import ChallengeComponent from '../components/gameScreenComponents/challengeComponent'
import { shuffle } from '../helpers/shuffle'
import { fillInSips, fillInChars, fillInNumbers, fillInPlayers, fillInChoice} from '../helpers/challengeRegex'
const GameScreen = ({ route, navigation }) => {
const playersNeeded = (challenge) => {
return 0
}
const popChallengeHandler = () => {
if (challenges.length > 1) {
let newChallenges = [...challenges];
newChallenges.shift()
processedChallenges = playChallenge(newChallenges)
setChallenges(processedChallenges)
}
else {
setChallenges([])
}
}
const playChallenge = (currentChallenges) => {
currentChallenges[0] = fillInChallenge(currentChallenges[0]);
currentChallenges[0]['nextRounds'].forEach(round => currentChallenges.splice(round[0],0,{
initialRound: round[1],
nextRounds: []
}))
return currentChallenges
}
const fillInChallenge = (challenge) => {
return fillInChoice(players)
}
const endGameHandler = () => {
Alert.alert("Ending game")
}
const players = route.params;
const [challenges, setChallenges] = useState(() => {
const initialState = playChallenge(shuffle(require('../data/challenges.json').deck.filter(challenge => players.length >= playersNeeded(challenge))));
return initialState;
});
if (challenges.length > 0)
return (<ChallengeComponent pressHandler={popChallengeHandler} text={challenges[0]['initialRound']} navigation={navigation}/>)
else
return (<ChallengeComponent pressHandler={endGameHandler} text="Het spel is afgelopen" navigation={navigation}/>)
}
export default GameScreen;
Navigator:
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import AddPlayerScreen from './screens/addPlayers';
import GameScreen from './screens/game';
console.disableYellowBox = true;
const RootStack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<RootStack.Navigator screenOptions={{headerShown: true}}>
<RootStack.Screen name="AddPlayers" component={AddPlayerScreen} />
<RootStack.Screen name="Game" component={GameScreen} />
</RootStack.Navigator>
</NavigationContainer>
);
};
export default App;
You can use this event listeners to doing some updates or else
navigation.addListener('blur', () => {console.log('focused Out')});
navigation.addListener('focus', () => {console.log('focused')});

Infinite loop error in Reactjs while using React Hooks

I am new to React and trying to use React Hooks but I am getting error.
I am not able to figure out which line of code causing infinite loop as in the console it says
Too many re-renders. React limits the number of renders to prevent an infinite loop
The above error occurred in the <ProcessingInvoiceScreen> component:
in ProcessingInvoiceScreen (at CreateInvoiceBySkid.js:49)
and from line 49 is the const ProcessingInvoiceScreen = () => {
import React, { Component,useState } from 'react';
import {connect} from "react-redux";
import * as actions from "../../../../actions";
class CreateInvoiceBySkid extends Component{
constructor(props){
super(props)
}
async componentDidMount(){
if (!this.props.authenticated && (this.props.authenticated.role !== "superAdmin" || this.props.authenticated.role === "admin" || this.props.authenticated.role === "operator")) {
this.props.history.push('/');
} else {
const user = this.props.authenticated;
this.props.getProcessingInvoiceSkids(user);
this.props.getProducts(user);
}
}
render(){
const ProcessingInvoiceScreen = () => {
const [closedSkids, setclosedSkids] = useState({});
const [selectedSkids, setSelectedSkids] = useState([]);
if(this.props.processingInvoiceSkids){
setclosedSkids(this.props.processingInvoiceSkids.rows);
}
console.log(this.props.processingInvoiceSkids);
return(
<div>
Hello World
</div>
)
}
return(
<div>
<ProcessingInvoiceScreen/>
</div>
)
}
}
const mapStateToProps=(state)=>{
return {
authenticated:state.authenticated,
errorMessage: state.errorMessage,
users: state.users,
processingInvoiceSkids: state.processingInvoiceSkids,
products: state.products
}
};
export default connect(mapStateToProps,actions)(CreateInvoiceBySkid);
What am I doing here that causes infinite loop?
This line is causing the error. Every time the component is renderer, the setclosedSkids function is called and the component is re-renderer again and again :
if(this.props.processingInvoiceSkids){
setclosedSkids(this.props.processingInvoiceSkids.rows);
}
Move this block to an useEffect callback function:
const ProcessingInvoiceScreen = ({processingInvoiceSkids}) => {
const [closedSkids, setclosedSkids] = useState({});
const [selectedSkids, setSelectedSkids] = useState([]);
useEffect(()=> {
if(processingInvoiceSkids){
setclosedSkids(processingInvoiceSkids.rows);
}
}, [processingInvoiceSkids.rows])
return(
<div>
Hello World
</div>
)
}
I recommend to move the function out of the parent component. Then in parent component:
return(
<div>
<ProcessingInvoiceScreen processingInvoiceSkid={this.processingInvoiceSkid}/>
</div>
)

React + Material UI - Textfield "onChange" never fired

I've tried to fire an onchange function when my Textfield is filled, but i can't figure out why this function is never fired, even if React devtool plugin for Chrome actually trigger the changes, any advice ?
import React, {Component} from 'react';
import {Tracker} from 'meteor/tracker';
import {Meteor} from 'meteor/meteor';
import {Links} from '../api/links';
import LinkListItem from './LinkListItem';
import {Session} from 'meteor/session';
import SearchLink from './SearchLink';
import Fuse from 'fuse.js';
export default class LinkList extends Component {
constructor(props) {
super(props);
this.state = {
links: [],
inputValue: ''
};
}
componentDidMount() {
this.linksTracker = Tracker.autorun(() => {
Meteor.subscribe('links');
const links = Links.find({visible:
Session.get('showVisible')}).fetch();
this.setState({links});
});
}
componentWillUnmount() {
this.linksTracker.stop();
}
renderLinksListItems() {
if (this.state.links.length === 0) {
return (
<div>
<h2 className="link">{Session.get('showVisible') ? 'No links found' : 'No hidden links found'}</h2>
</div>
);
}
console.log(this.state.links);
return this.state.links.map((link) => {
const shortUrl = Meteor.absoluteUrl(link._id);
return <LinkListItem key={link._id} shortUrl={shortUrl} {...link}/>;
});
}
_onChange(e) {
if(e.target.value === "") {
return;
}
var fuse = new Fuse(this.state.links, { keys: ["url"]});
var result = fuse.search(e.target.value);
this.setState({
inputValue: e.target.value,
links: result
});
}
render() {
return (
<div>
<div>
<SearchLink onChange={this._onChange} value={this.state.inputValue}/>
</div>
<div>{this.renderLinksListItems()}</div>
</div>
);
}
}
My Textfield component :
import React from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import TextField from 'material-ui/TextField';
const muiTheme = getMuiTheme({
palette: {
primary1Color: '#ef6c00'
}
})
const SearchLink = () => (
<MuiThemeProvider muiTheme={muiTheme}>
<TextField floatingLabelText="Search a Link" name="searchLink" fullWidth={true}/>
</MuiThemeProvider>
);
export default SearchLink;
Thank you for your help!
Do these changes:
1. Bind the method in Parent component LinkList, because you are using this.setState inside onChange method, if you don't bind it, it will throw the error, bind it like this:
<SearchLink onChange={this._onChange.bind(this)} value={this.state.inputValue}/>
or define the binding in constructor.
2. You are passing the event and value in props, so you need to define those values in TextField, like this:
const SearchLink = (props) => (
<MuiThemeProvider muiTheme={muiTheme}>
<TextField
onChange = {props.onChange}
value = {props.value}
floatingLabelText = "Search a Link"
name = "searchLink"
fullWidth = {true}/>
</MuiThemeProvider>
);

Categories