React Native issues passing functions - javascript

I am new to React Native, and what i am trying to do is, that i would like to pass getUPCfromApi(upc) to ScanditSDK.js component, inside the onScan function. But i get this error see attached img.
Screenshot of error message
Api.js
import React, { Component } from 'react';
import ScanditSDK from './components/ScanditSDK'
export default class Api extends Component{
getUPCfromApi = (upc) => {
try {
let response = fetch(
`https://api.upcdatabase.org/product/${upc}/API_KEY`);
let responseJson = response.json();
return responseJson;
console.log('response',responseJson);
} catch (error) {
console.error(error);
}
}
render(){
return(
<ScanditSDK
getUPCfromApi={this.getUPCfromApi}
/>
)
}
}
ScanditSDK.js contains scanner module. Inside the onScan method i am calling getUpcFromApi(upc) which i made inside Api.js
ScanditSDK.js
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
findNodeHandle,
View
} from 'react-native';
import {
BarcodePicker,
ScanditModule,
ScanSession,
Barcode,
SymbologySettings,
ScanSettings
} from 'react-native-scandit';
ScanditModule.setAppKey('APIKEY');
export class ScanditSDK extends Component {
constructor(props){
super(props)
this.state = {
upc: '',
}
}
componentDidMount() {
this.scanner.startScanning();
}
render() {
return (
<View style={{
flex: 1,
flexDirection: 'column'}}>
<BarcodePicker
onScan={(session) => { this.onScan(session) }}
scanSettings= { this.settings }
ref={(scan) => { this.scanner = scan }}
style={{ flex: 1 }}/>
</View>
);
}
onScan = (session) => {
this.setState({upc:session.newlyRecognizedCodes[0].data })
alert(session.newlyRecognizedCodes[0].data + " " + session.newlyRecognizedCodes[0].symbology);
this.props.getUPCfromApi(this.state.upc)
}
}

You should use props to access your function. change your onScan function as below
onScan = (session) => {
this.setState({upc:session.newlyRecognizedCodes[0].data })
alert(session.newlyRecognizedCodes[0].data + " " + session.newlyRecognizedCodes[0].symbology);
this.props.getUPCfromApi(this.state.upc)
}
And in your Api component. Bind your function in constructor.
constructor(props){
super(props)
this.getUPCfromApi = this.getUPCfromApi.bind(this)
}

Related

TypeError _this2.getWifiList().bind is not a function. React Native componentDidMount

I'm trying to get my app to refresh a select components list of options. The list will show a selection of wifi hotspots and I want the app to scan for them every 5 seconds, so I followed this guide: https://blog.stvmlbrn.com/2019/02/20/automatically-refreshing-data-in-react.html
But when I run the app, I get this error:
Error
Possible Unhandled Promise Rejection (id: 0):
TypeError: _this2.getWifiList().bind is not a function. (In '_this2.getWifiList().bind((0, _assertThisInitialized2.default)(_this2))', '_this2.getWifiList().bind' is undefined)
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:187369:75
tryCallOne#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27870:16
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:27971:27
_callTimer#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:31410:17
_callImmediatesPass#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:31449:17
callImmediates#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:31666:33
__callImmediates#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3610:35
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3396:34
__guard#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3593:15
flushedQueue#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3395:21
flushedQueue#[native code]
invokeCallbackAndReturnFlushedQueue#[native code]
This error comes up 10 times in a second. I tried removing the bind but I get the same error.
MainScreen.js
import React, {useState} from 'react';
import { StyleSheet, PermissionsAndroid, Linking, View, TouchableOpacity } from 'react-native';
import { IndexPath, Layout, Text, Button, Select, SelectItem } from '#ui-kitten/components';
import { Icon } from 'react-native-eva-icons';
import {styles} from '../styles'
import WifiManager from "react-native-wifi-reborn";
class LocationSelector extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedIndex : (new IndexPath(0)),
wifiList: null,
intervalID: null,
}
}
componentDidMount() {
this.getWifiList();
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
getWifiList = async () => {
WifiManager.setEnabled(true);
await WifiManager.reScanAndLoadWifiList()
.then((data) => {
this.state.wifiList = data
this.intervalID = setTimeout( async () => {await this.getWifiList().bind(this)}, 5000);
});
}
renderOption = (title) => (
<SelectItem title={title}/>
)
render() {
console.log(this.state.selectedIndex);
const data = [
'Venue1',
'Venue2',
'Venue3',
];
const displayValue = data[this.state.selectedIndex.row];
return(
<Select
style={styles.select}
size="large"
placeholder='Default'
value={displayValue}
disabled={this.props.disabled}
accessoryLeft={PinIcon}
selectedIndex={this.state.selectedIndex}
onSelect={(index) => {(this.state.selectedIndex = index); this.forceUpdate()}}>
{data.map(this.renderOption)}
</Select>
);
}
}
class MainScreen extends React.Component {
constructor(props) {
super(props);
this.navigation = props.navigation
this.state = {
isCheckedIn: false,
}
}
render() {
return (
<Layout style={styles.container}>
<LocationSelector />
</Layout>
);
}
}
export default MainScreen;
The issue is in the way you are calling .bind():
this.getWifiList().bind(this)
Note that .bind() is a method of the Function prototype, therefore, is available only when called on a function reference.
In this case, you are calling .bind() on this.getWifiList(), which is the return value of getWifiList, not the functon itself.
To fix the error you are getting, you just need to call it on the function:
this.getWifiList.bind(this)

Where should I call a method to use data from it?

I'd like to call getAlbums() method so I can use the data from the get request and display album data on the client side. I don't know where to call it though. I tried to call it in render() but it creates an infinite loop.
Albums.js
import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";
export class Albums extends Component {
constructor(props) {
super(props);
this.state = { albums: [] };
this.getAlbums = this.getAlbums.bind(this);
}
async getAlbums() {
const {
match: { params },
} = this.props;
console.log(params.id);
try {
const res = await axios.get(
`http://localhost:4000/albums/${encodeURIComponent(params.id)}`,
{
params: {
id: params.id,
},
}
);
console.log(`Returned album data from the server: ${res}`);
this.setState({ albums: res.data });
} catch (err) {
console.log(err);
}
}
render() {
return (
<>
<div className="container" style={{ color: "white" }}>
hello
</div>
</>
);
}
}
export default Albums;
I wanna do something like this inside the div.
this.state.albums.map((album) => (<AlbumCard img={album.img}/>))
The reason you get an infinite loop is because you're calling setState in render. Here is what's happening behind the scenes:
1.getAlbums is called in the render method.
2.The function triggers setState.
3.setState causes re-render.
4.In the render method, getAlbums is called again.
Repeat 1-4 infinitely!
Here's is what you could do:
Create a button and bind getAlbums as a method to the onClick event handler.
2.Run getAlbums on ComponentDidMount like so:
componentDidMount() {
this.getAlbums();
}
componentDidMount() is the best place for making AJAX requests.
The componentDidMount() method will set state after the AJAX call fetches data. It will cause render() to be triggered when data is available.
Here is the working example with componentDidMount()
import React, { Component } from "react";
import { useParams } from "react-router-dom";
import axios from "axios";
import AlbumCard from "./AlbumCard";
export class Albums extends Component {
constructor(props) {
super(props)
this.state = { albums: [] }
}
componentDidMount() {
axios.get(
`http://localhost:4000/albums/${encodeURIComponent(this.props.id)}`,
{ params: { id: this.props.id } }
)
.then(response => {
console.log(`Returned album data from the server: ${res}`)
this.setState({ albums: response.data })
}
)
.catch(e => {
console.log("Connection failure: " + e)
}
)
}
render() {
return (
<div>
{/* Code for {this.state.albums.map(item => )} */}
{/* render() method will be called whenever state changes.*/}
{/* componentDidMount() will trigger render() when data is ready.*/}
</div>
)
}
}
export default Albums
More information:
https://blog.logrocket.com/patterns-for-data-fetching-in-react-981ced7e5c56/
use componentDidMount()
componentDidMount(){
getAlbums()
}

Unit test with enzyme

I have the following component in my React-Native application. I have been asked to write a unit test using jest and enzyme for this, but I'm new to unit test. So, how to break this down and write proper tests is beyond my knowledge. Could someone help me with this??
import React, { Component } from 'react';
import { View } from 'react-native';
import { WebView } from 'react-native-webview';
import { Button, Loader, ScreenContainer } from '../../../../../components';
import {
decodeBase64,
hasWordsInString,
setFirstAndFamilyName,
} from '../../../../../library/Utils';
import { url, searchWords, signUpMethods } from '../../../../../config';
import { SIGN_UP_FORM } from '../../../../constants/forms';
// tslint:disable-next-line: max-line-length
const response = 'some-token';
class MyWebView extends Component {
state = {
loaderStatus: true,
};
stopLoader = () => {
this.setState({ loaderStatus: false });
}
startLoader = () => {
this.setState({ loaderStatus: true });
}
displayLoader = () => {
const { loaderStatus } = this.state;
return loaderStatus && <Loader />;
}
render() {
const { navigation, addFormData, setSignUpMethod } = this.props;
return (
<View style={{ flex: 1 }}>
<WebView
source={{ uri: url }}
onLoadStart={() => this.startLoader()}
onLoad={() => this.stopLoader()}
onLoadEnd={(syntheticEvent) => {
const { nativeEvent } = syntheticEvent;
if (nativeEvent.title === 'Consent Platform') {
if (hasWordsInString(nativeEvent.url, searchWords)) {
const { address, ...rest } = decodeBase64(response).data;
const userName = setFirstAndFamilyName(rest.name);
rest.firstName = userName.firstName;
rest.familyName = userName.familyName;
addFormData({ form: SIGN_UP_FORM, data: { values: { ...rest, ...address } } });
setSignUpMethod(signUpMethods.MY_INFO);
navigation.replace('ConfirmName', rest);
}
}
}}
/>
{this.displayLoader()}
</View>
);
}
}
export default MyWebView;
How can I write some proper unit tests for the above code using jest and enzyme? What are the principles that I have to follow? What makes a unit test a better one?
Here is a shallow test, then you can pass in your own dummy data and compare the snapshots, so basically if anyone changes any of your custom components that are used in this component your test will fail
import "react-native"
import React from "react"
import { shallow } from "enzyme"
import MyWebView from "../../App/Components/MyWebView"
test("Should render CustomHeader", () => {
const wrapper = shallow(<MyWebView />)
expect(wrapper).toMatchSnapshot()
})

How to get async data without reloading whole app

I am trying when the user clicks on bottomTabNavigator the component screen will reload. I mean in my first component screen "AnotherA.js", I am using textinput which store user entered data in async storage and in another component "AnotherB.js" I am using get() of async storage to show my stored data on the screen. I am able to see the stored data the first time while reloading the whole app.
I am trying to get data without reloading, the whole app, by navigating with bottomTabNavigator it displays immediately.
//App.js
import React, { Component } from "react";
import { createAppContainer } from 'react-navigation';
import { createMaterialBottomTabNavigator } from 'react-navigation-material-bottom-tabs';
import { TabNavigator } from 'react-navigation';
import AnotherA from './AnotherA';
import AnotherB from './AnotherB';
const AppNavigator = createMaterialBottomTabNavigator(
{
AnotherA: { screen: AnotherA },
AnotherB: { screen: AnotherB }
},
{
initialRouteName: 'AnotherA',
activeColor: '#f0edf6',
inactiveColor: '#3e2465',
barStyle: { backgroundColor: '#694fad' },
pressColor: 'pink',
},
{
//tabBarComponent: createMaterialBottomTabNavigator /* or TabBarTop */,
tabBarPosition: 'bottom',
defaultnavigationOptions: ({ navigation }) => ({
tabBarOnPress: (scene, jumpToIndex) => {
console.log('onPress:', scene.route);
jumpToIndex(scene.index);
},
}),
}
);
const AppContainer = createAppContainer(AppNavigator);
export default AppContainer;
//AnotherA.js
import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from './styles';
export default class AnotherA extends Component {
constructor(props) {
super(props);
this.state = {
myKey: '',
text1: '',
}
}
async getKey() {
try {
//const value = await AsyncStorage.getItem('#MySuperStore:key');
const key = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: key,
});
} catch (error) {
console.log("Error retrieving data" + error);
}
}
async saveKey(text1) {
try {
await AsyncStorage.setItem('#MySuperStore:key', text1);
} catch (error) {
console.log("Error saving data" + error);
}
}
async resetKey() {
try {
await AsyncStorage.removeItem('#MySuperStore:key');
const value = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: value,
});
} catch (error) {
console.log("Error resetting data" + error);
}
}
componentDidMount() {
this.getKey();
}
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Enter Data"
value={this.state.myKey}
onChangeText={(value) => this.setState({ text1: value })}
multiline={true}
/>
<Button
onPress={() => this.saveKey(this.state.text1)}
title="Save"
/>
<Button
//style={styles.formButton}
onPress={this.resetKey.bind(this)}
title="Reset"
color="#f44336"
accessibilityLabel="Reset"
/>
</View>
)
}
}
//AnotherB.js
import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from './styles';
export default class AnotherB extends Component {
constructor(props) {
super(props);
this.state = {
myKey: '',
text1: '',
}
}
async getKey() {
try {
//const value = await AsyncStorage.getItem('#MySuperStore:key');
const key = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: key,
});
} catch (error) {
console.log("Error retrieving data" + error);
}
}
componentDidMount() {
this.getKey();
}
render() {
//const { navigate } = this.props.navigation;
//const { newValue, height } = this.state;
return (
<View style={styles.container}>
<Text>{this.state.myKey}</Text>
</View>
)
}
}
Please suggest, I am new to React-Native.
The issue is that you are retrieving the value from AsyncStorage when the component mounts. Unfortunately that isn't going to load the value on the screen when you switch tabs. What you need to do is subscribe to updates to navigation lifecycle.
It is fairly straight forward to do. There are four lifecycle events that you can subscribe to. You can choose which of them that you want to subscribe to.
willFocus - the screen will focus
didFocus - the screen focused (if there was a transition, the transition completed)
willBlur - the screen will be unfocused
didBlur - the screen unfocused (if there was a transition, the transition completed)
You subscribe to the events when the component mounts and then unsubscribe from them when it unmounts. So when the event you have subscribed to happens, it will call the function that you have put into the subscriber's callback.
So you can do something like this in you AnotherB.js:
componentDidMount() {
// subscribe to the event that we want, in this case 'willFocus'
// when the screen is about to focus it will call this.getKey
this.willFocusSubscription = this.props.navigation.addListener('willFocus', this.getKey);
}
componentWillUnmount() {
// unsubscribe to the event
this.willFocusSubscription.remove();
}
getKey = async () => { // update this to an arrow function so that we can still access this, otherwise we'll get an error trying to setState.
try {
const key = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({
myKey: key,
});
} catch (error) {
console.log("Error retrieving data" + error);
}
}
Here is a quick snack that I created showing it working, https://snack.expo.io/#andypandy/navigation-life-cycle-with-asyncstorage
You can try to add then after getItem
AsyncStorage.getItem("#MySuperStore:key").then((value) => {
this.setState({
myKey: value,
});
})
.then(res => {
//do something else
});

how to call function inside reactjs render method properly?

I want to fetch data from server & show it inside tables. When I directly put code inside the render it works. But, When I encapsulate inside the addElementsToDisplay function & call that function inside render method it doesn't work. Actually, the function gets called, but response is not rendered in table format. Below is my code:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Button } from 'semantic-ui-react';
import ResponseRenderer from './responseRenderer';
import "./App.css";
const responseDataContext = React.createContext({});
class App extends Component {
constructor(props) {
super(props);
this.getPastJobs = this.getPastJobs.bind(this);
this.addElementsToDisplay = this.addElementsToDisplay.bind(this);
this.state = { pastJobs: [] }
}
render() {
return (
<div className="App">
<Button onClick={this.getPastJobs}>Get Past Jobs</Button>
<h1> Hello, World! </h1>
{this.addElementsToDisplay()}
</div>
);
}
addElementsToDisplay() {
console.log("state: ", JSON.stringify(this.state));
this.state.pastJobs.map((value, index) => {
return <ResponseRenderer key={Math.random()} data={value} />
});
}
getPastJobs() {
fetch('http://localhost:9090/getPastJobs', {
method: 'POST',
body: JSON.stringify({})
})
.then((response) => {
if (response.status !== 200) {
return;
}
response.json().then((jobs) => {
console.log(jobs);
this.setState({ pastJobs: jobs.data })
});
})
.catch((err) => {
console.log(err.message, err.stack);
});
}
}
export default App;
You are not returning the response and hence it is not rendered, just return the mapped response and it will work fine
addElementsToDisplay() {
console.log("state: ", JSON.stringify(this.state));
return this.state.pastJobs.map((value, index) => {
return <ResponseRenderer key={Math.random()} data={value} />
});
}

Categories