'state' is not defined (no-undef) - react-native

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;

Related

Redux-Saga Component Setup

I'm having trouble getting redux-saga to work. I'm thinking the issue lies somewhere between the saga_component.js and saga_screen.js files. It may be I'm not using the correct syntax to map out the API?
I'm getting eror:
"undefined is not a function (near '...ConnectData.map' ".
This is located in the Saga_component.js file.
I've been working on this for a while now, not sure what to adjust at this point. Would greatly appreciate some guidance. This is a link to the repo. All screens and components can be found in the 'src' file.
App.js File
import React from "react";
import Setup from "./src/boot/setup";
import { Provider } from 'react-redux';
import store from './src/store';
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<Setup/>
</Provider>
);
}}
Store.js
import {createStore, applyMiddleware} from 'redux';
import createSagaMiddleware from 'redux-saga';
import AllReducers from '../src/reducers';
import rootSaga from '../src/saga';
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
AllReducers,
applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);
export default store;
saga.js
import { call, put, takeEvery, takeLatest } from "redux-saga/effects";
import { REQUEST_API_DATA, receiveApiData } from "./actions";
import { fetchData } from "./api";
function* getApiData(action) {
try {
// do api call
const data = yield call(fetchData);
yield put(receiveApiData(data));
} catch (e) {
console.log(e);
}
}
export default function* rootSaga() {
yield takeLatest(REQUEST_API_DATA, getApiData);
}
data.js (this is the reducer)
import { RECEIVE_API_DATA } from "../actions";
export default (state = {}, { type, data }) => {
switch (type) {
case RECEIVE_API_DATA:
return data;
default:
return state;
}
};
actionsCreators.js
import { REQUEST_API_DATA, RECEIVE_API_DATA} from './types';
export const requestApiData = () => {
return {
type: REQUEST_API_DATA
}
};
export const receiveApiData = (data) => {
return {
type: RECEIVE_API_DATA,
data
}
};
saga_component.js
import React from "react";
import { AppRegistry, View, StatusBar } from "react-native";
import { Container, Body, Content, Header, Left, Right, Icon, Title,
Input, Item, Label, Button, Text } from "native-base";
export default class SagaComponent extends React.Component {
renderList() {
const ConnectData = this.props.data;
return ConnectData.map((data) => {
return (
<View style={{width: 280}}>
<Text style={styles.TextLight}><Text style={styles.TextDark}>Dest City:</Text> {data.name}</Text>
<Text style={styles.TextLight}><Text style={styles.TextDark}>ETA:</Text> {data.email}</Text>
</View>
);
});
}
render() {
return (
<View>
<Label>Username</Label>
{this.renderList()}
</View>
);
}
}
saga_screen.js
import React, { Component } from "react";
import { Container, Text, Button } from "native-base";
import { View, StatusBar } from "react-native";
import { connect } from "react-redux";
import styles from "../styles/styles";
import { bindActionCreators } from "redux";
import { requestApiData } from "../actions";
import SagaComponent from '../components/saga_component';
class SagaScreen extends React.Component {
render() {
return (
<Container style={styles.container}>
<View style={{marginTop: 50 }}>
<SagaComponent data={this.props.data}/>
</View>
<Button block style={styles.Home_btns}
onPress={() => this.props.navigation.navigate("Home")}>
<Text>Home</Text>
</Button>
</Container>
);
}
}
function mapStateToProps(state) {
return {
data: state.data,
};
}
const mapDispatchToProps = dispatch =>
bindActionCreators({ requestApiData }, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(SagaScreen);
Api.js
export const fetchData = async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await response.json();
return data;
} catch (e) {
console.log(e);
}
};
index.js(reducer index.js file)
import { combineReducers } from 'redux';
import data from "./data";
const AllReducers = combineReducers({
data,
});
export default AllReducers;
It looks like the problem could be in your reducer. Instead of returning data you should return { data };
Also, as an aside, you might want to guard against falsey data in your saga_component (ConnectData || []).map((data) => {

Accessing navigation props - react-navigation

I just have a question regarding react-navigation.
I understand that the navigation props becomes accessible when a screen is rendered from the stacknavigator.
But how do you access the navigation props if the screen is not rendered by the stacknavigator?
Like this:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
StyleSheet,
Text,
View,
} from 'react-native';
import Swiper from 'react-native-swiper';
import Menu from './Menu';
class HomeSwiper extends Component {
static propTypes = {
navigation: PropTypes.object,
};
render() {
return (
<Swiper showsButtons>
<View>
<Menu
navigationProps={this.props.navigation}
/>
</View>
<View>
<Text>Hello Swiper</Text>
</View>
</Swiper>
);
}
}
export default HomeSwiper;
Wherein Menu is:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { AsyncStorage, TouchableOpacity, Text, BackHandler, Alert } from 'react-native';
import { StandardContainerIOS } from '../components/Container';
import { StandardButton } from '../components/Buttons/';
class Menu extends Component {
static propTypes = {
navigation: PropTypes.object,
};
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
const headerLeft = (
<TouchableOpacity
onPress={params.handleRedirect ? params.handleRedirect : () => null}
>
<Text>Logout</Text>
</TouchableOpacity>
);
return {
headerLeft,
};
};
constructor(props) {
super(props);
this.state = {
email: '',
petName: [],
numberOfPets: '',
};
}
getInitialState() {
return {
petName: ['No Name'],
};
}
async componentWillMount() {
try {
const value = await AsyncStorage.getItem('email');
if (value !== null) {
// We have data!!
}
} catch (error) {
// Error retrieving data
}
this.props.navigation.setParams({
handleRedirect: this.handlePressLogout,
});
this.getEmail();
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}
render() {
return (
<StandardContainerIOS>
<StandardButton backgroundColor="#6D4C41" title="View Pet" onPress={this.handleIndexView} />
<StandardButton backgroundColor="#6D4C41" title="Register Pet" onPress={this.handlePressRegisterPets} />
<StandardButton backgroundColor="#6D4C41" title="Logout" onPress={this.handlePressLogout} />
</StandardContainerIOS>
);
}
}
export default Menu;
I've removed the other function definition to cut the post a little shorter. The Menu screen was working fine when it was rendered from the stacknavigator. Im trying to incorporate swiping in my app.
Any suggestions?

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'

React Native Router Flux: passing params between scenes

I have a list of items (jobs) and when an item (job) is being selected, a new scene is being opened. I want the ID of the selected item to be passed from the scene with the list to the other scene with the details about the selected item (job) without using Redux.
Router
import React from 'react';
import { Scene, Router } from 'react-native-router-flux';
import JobsList from './components/JobsList';
import Job from './components/Job';
const RouterComponent = () => {
return (
<Router>
<Scene key="jobs" component={JobsList} initial />
<Scene key="Job" component={Job} title="Test" />
</Router>
);
};
export default RouterComponent;
Jobs list
import React, { Component } from 'react';
export default class JobsList extends Component {
render() {
return (
<TouchableOpacity onPress={() => { Actions.Job({ jobId: jobId }) }}>
...
</TouchableOpacity>
);
}
}
Job
import React, { Component } from 'react';
export default class Job extends Component {
constructor() {
super();
this.state = {
job: {}
};
axios.get(
// PROBLEM: this.props.jobId is empty
`http://api.tidyme.dev:5000/${this.props.jobId}.json`,
{
headers: { Authorization: 'Token token=123' }
}
).then(response => this.setState({
job: response.data
}));
}
render() {
return (
<Text>{this.state.job.customer.firstName}</Text>
);
}
}
You should call super(props) if you want to access this.props inside the constructor.
constructor(props) {
super(props);
console.log(this.props);
}
The best practice is defining Components as pure functions:
const Job = ({ job, JobId}) => {
return (
<Text>{job.customer.firstName}</Text>
);
}
otherFunctions() {
...
}

React-Native error this.setState is not a function

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));