React-Native error this.setState is not a function - react-native

I'm using below lib to implement a callback (onSuccess, onError) for every ApiRequest. But I have a problem when update state when event is trigged. I tried to remove all stuffs just keep the base logic. I don't know why it error.
Lib: https://www.npmjs.com/package/react-native-simple-events
Below is my code
ApiRequest.js
import Events from 'react-native-simple-events';
export function login(email, password) {
Events.trigger('LoginSuccess', 'response');
}
Login.js
import React, { Component, } from 'react'
import {
View,
Text,
} from 'react-native'
import Events from 'react-native-simple-events';
import * as request from '../../network/ApiRequest'
class LoginScreen extends Component {
static propTypes = {}
static defaultProps = {}
constructor(props) {
super(props)
this.state = {
status: "new"
}
}
componentDidMount() {
Events.on('LoginSuccess', 'myID', this.onLoginSuccess);
request.login("abc","def")
}
componentWillUnmount() {
Events.rm('LoginSuccess', 'myID');
}
onLoginSuccess(data){
this.setState({ //=>error here
status : "done"
});
}
render() {
return (
<View>
<Text>
{this.state.status}
</Text>
</View>
)
}
}
let me know if you need more information

You need to bind this on the onLoginSuccess method:
Events.on('LoginSuccess', 'myID', this.onLoginSuccess.bind(this));

Related

function componentDidMount not firing in react native

The function componentDidMount is not firing.
This is some of my code:
import React, { Component } from 'react';
import { Block } from 'galio-framework';
export function FriendRequests ( ) {
const username = 'abcd';
componentDidMount = () => {
alert("abcd");
}
return (
line number 37: <Block>....</Block>
)
}
You are using the functional component which doesn't have the lifecycle methods.
Solution 1:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
class FriendRequests extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount = () => {
alert("abcd");
}
render() {
return (
<View>
<Text> Your text Here </Text>
</View>
);
}
}
export default FriendRequests;
Solution 2:
If you want to use it as functional component then you can use the React Hook and can make use of useEffect() method from the hook instead of componentDidMount. method to handle after render stuff.
First of all,
export function FriendRequests ( ) {
componentDidMount = () => {
alert("abcd");
}
return (
....
)
}
this is a functional component, and functional component dont have any inbuilt functions like componentDidMount. Only class based components have access, So try this:
UPDATE:
export class FriendRequests extends React.Component {
componentDidMount() {
alert("abcd");
}
render() {
return (
<View>
<Text>hey</Text>
</View>
);
}
}
hope it helps. feel free for doubts

Undefined Unstated Container in a React Native Component using React Navigation

My problem is That I want to access a Container in a component but it seems to be undefined.
undefined alert image
I am using Unstated and as you can see this is my code in the container file (login-container.js):
import { Container } from 'unstated'
class LoginContainer extends Container {
constructor(props){
super(props)
this.state = {
stepNumber: 0,
}
}
}
export default new LoginContainer()
And this is app.js:
import React, { Component } from 'react'
import { createStackNavigator, createSwitchNavigator } from 'react-navigation'
import { Provider } from 'unstated'
import LoginContainer from './containers/login-container'
import Home from './screens/home'
import Splash from './screens/splash'
import Login from './screens/login'
import Intro from './screens/intro'
export default class App extends Component {
render() {
return (
<Provider inject={[LoginContainer]}>
<AuthStack/>
</Provider>
)
}
}
const SplashStack = createStackNavigator(...)
const AppStack = createStackNavigator(...)
const AuthStack = createStackNavigator(
{
Intro: { screen: Intro},
Login: { screen: Login}
},
{
headerMode: "none",
initialRouteName: "Intro"
}
)
const SwitchNavigator = createSwitchNavigator(...)
And this would be login.js:
import React, { Component } from 'react'
import { Text, View } from 'react-native'
export default class Login extends Component {
constructor(props){
super(props)
}
render() {
// const { state: {stepNumber} } = this.props.loginContainer
alert(this.props.LoginContainer)
return (
<View>
<Text> someText </Text>
</View>
)
}
}
I previously tried to use Subscribe component to inject the container to my app but I got the same thing I am getting here.
Using
- react-native 0.58.6
- react-navigation 2.13.0 (due to some bugs in v3)
- unstated 2.1.1
What's really great about Unstated is how simple it is to implement.
Just wrap your render component in Unstated's <Subscribe to></Subscribe> tags and you're good to go. Whenever you setState() in the Container, all Components that Subscribe to it get re-rendered with the Container's updated state property values available to them.
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { Subscribe } from 'unstated';
import LoginContainer from './containers/login-container';
export default class Login extends Component {
constructor(props){
super(props)
}
render() {
return (
<Subscribe to={[LoginContainer, AnotherContainer]}>
{(container, another) => (
<View>
<Text>{container.state.stepNumber}</Text>
</View>
})
</Subscribe>
);
}
}
UPDATE: Or do it in this HOC way. After creating this:
WithUnstated.js
import React, { PureComponent } from "react";
import { Subscribe } from "unstated";
import DefaultStore from "../store/DefaultStore";
const withUnstated = (
WrappedComponent,
Stores = [DefaultStore],
navigationOptions
) =>
class extends PureComponent {
static navigationOptions = navigationOptions;
render() {
return (
<Subscribe to={Stores}>
{(...stores) => {
const allStores = stores.reduce(
(acc, v) => ({ ...acc, [v.displayName]: { ...v } }),
{}
);
return <WrappedComponent {...allStores} {...this.props} />;
}}
</Subscribe>
);
}
};
export default withUnstated;
Then wrap your component like so:
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { Subscribe } from 'unstated';
import LoginContainer from './containers/login-container';
import AnotherContainer from './containers/another-container';
class Login extends Component {
constructor(props){
super(props)
}
render() {
const {LoginContainer: container} = this.props;
return (
<View>
<Text>{container.state.stepNumber}</Text>
</View>
);
}
}
export default withUnstated(Login, [LoginContainer, AnotherContainer])

Exporting a value from a function or default in React Native

I have the following the code like this.
import React, {Component} from 'react'
import {AsyncStorage} from 'react-native'
export default {
baseURL: 'http://mywebsite.com/JsonApi/',
};
In the code, I am using the base url for api calls. Now, sometimes, I want to add a sub domain to the domain. And, the sub domain values are taking from AsyncStorage. How can I modify the code to do that?
You can get value from Async storage and set that into state.
import * as React from 'react';
import { View } from 'react-native';
import { AsyncStorage } from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
subdomain: '',
};
}
retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('your subdomain stored key');
this.setState({ subdomain: value });
const baseURL = `http://${this.state.subdomain}.mywebsite.com/JsonApi/`;
} catch (error) {
console.log(error);
}
}
componentDidMount() {
this.retrieveData();
}
render() {
return (
<View/>
);
}
}

'state' is not defined (no-undef)

I am complete noob and am just following a tutorial in react-native on udemy. However, I have reached a wall and cannot find a solution anywhere?
Currently I am getting an error from ESLint showing that state is undefined.
Here is the complete code:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';
class AlbumList extends Component {
state = { albums: [] }; //state is underlined
ComponentWillMount() {
axios.get('https:/rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }));
}
renderAlbums() {
render() {
console.log(this.state);
return (
<View>
{this.renderAlbums()}
</View>
**strong text**);
}
}
export default AlbumList;
Has there been any update regarding defining 'state' in React-Native?
Sincerely appreciate the help!
Try this out.
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';
class AlbumList extends Component {
constructor(props){
super(props);
this.state = {
albums: []
};
this.renderAlbums = this.renderAlbums.bind(this);
}
componentWillMount() {
axios.get('https:/rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }));
}
renderAlbums() {
return (
<View /> // return your Albums here as you need
);
}
render() {
return (
<View>
{this.renderAlbums()}
</View>
);
}
}
export default AlbumList;

Headless Task use inside component with React Native

I am trying to run a background task using headlessjs in react-native. The problem is that I am unable to access the async task inside the component in order to show it on the view. Here's my default component.
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
NativeModules
} from 'react-native';
module.exports = NativeModules.ToastAndroid;
someTask = require('./SomeTaskName.js');
export default class test2 extends Component {
constructor() {
super()
this.state = {
myText: 'My Original Text'
}
}
updateText = () => {
this.setState({myText: 'My Changed Text'});s
}
componentDidMount(){
this.setState({myText: someTask});
someTask.then(function(e){ //<--- error
console.log("lala" + e);
});
}
render() {
return (
<View>
<Text>
abc
</Text>
</View>
);
}
}
AppRegistry.registerComponent('test2', () => test2);
AppRegistry.registerHeadlessTask('SomeTaskName', () => someTask);
As mentioned in the code, I get the error undefined is not a function. I don't know how to make this work. My SomeTaskName.js looks like this.
SomeTaskName.js
module.exports = async (taskData) => {
return taskData.myname;
}
The idea is to simply get the data from the service and show it on the UI.
The solution was to simply move the code inside the componentDidMount function. Here's how I achieved it.
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
Image
} from 'react-native';
export default class test2 extends Component {
constructor() {
super()
this.state = {
myText: '1'
}
}
componentWillUnmount() {
}
componentDidMount(){
someTask = async (taskData) => {
this.setState({ myText: taskData.myname});
}
};
}
render() {
return (<Text>Working</Text>);
}
}
AppRegistry.registerHeadlessTask('SomeTaskName', () => someTask);
AppRegistry.registerComponent('test2', () => test2);
You can replace :
someTask = require('./SomeTaskName.js');
by
import SomeTaskName from './SomeTaskName'