Connect() not working ( no error ) in Redux React Native app - react-native

I'm trying to create a small counting number app, all it does is when I click increase, the counter value increase.
And I'm trying to apply Redux to it, but it not working.
Because there is no error thrown, I really don't know where to fix. Please help.
Thank you in advance!
I checked the store.getState() and the appReducer , it worked just fine. I think the problem is that I did something wrong and the connect() didn't work probably.
/* STORE */
import { createStore } from 'redux';
const INCREASE = 'increase';
const DECREASE = 'decrease';
const increase = () => { type: INCREASE }
const decrease = () => { type: DECREASE }
const initialState = { count: 0 };
function appReducer(state = initialState, action) {
switch (action.type) {
case INCREASE:
return { count: state.count + 1 };
case DECREASE:
return { count: state.count - 1 };
}
return state;
}
const store = createStore(appReducer);
/* COMPONENT */
export class Main extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={{ flex: 1 }}>
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#4a99f9',
}}>
<Text
style={{
color: 'white',
fontSize: 100,
fontWeight: 'bold',
textAlign: 'center',
}}>
{ this.props.count }
</Text>
</View>
<View
style={{
flex: 1,
padding: 30,
alignItems: 'center',
backgroundColor: '#fff711',
}}>
<TouchableOpacity
style={{
margin: 5,
width: 200,
height: 50,
backgroundColor: '#51f772',
justifyContent: 'center',
}}
onPress={increase}>
<Text
style={{
color: 'white',
textAlign: 'center',
fontWeight: 'bold',
}}>
Increase
</Text>
</TouchableOpacity>
<TouchableOpacity
style={{
margin: 5,
width: 200,
height: 50,
backgroundColor: '#ff5c38',
justifyContent: 'center',
}}
onPress={decrease}>
<Text
style={{
color: 'white',
textAlign: 'center',
fontWeight: 'bold',
}}>
Decrease
</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
/* ROOT */
import { connect } from 'react-redux';
const mapStateToProps = state => { count: state.count };
const mapDispatchToProps = dispatch => {
return {
increase: () => dispatch(increase()) ,
decrease: () => dispatch(decrease())
}
};
const AppContainer = connect(mapStateToProps , mapDispatchToProps)(Main);
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { Provider } from 'react-redux';
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<AppContainer />
</Provider>
);
}
}

Hi change your component file to below code and rerun. You forgot to dispatch your actions.
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
TouchableOpacity
} from "react-native";
import { connect } from 'react-redux'
class CounterApp extends Component {
render() {
return (
<View style={styles.container}>
<View style={{ flexDirection: 'row', width: 200, justifyContent: 'space-around' }}>
<TouchableOpacity onPress={() => this.props.increaseCounter()}>
<Text style={{ fontSize: 20 }}>Increase</Text>
</TouchableOpacity>
<Text style={{ fontSize: 20 }}>{this.props.counter}</Text>
<TouchableOpacity onPress={() => this.props.decreaseCounter()}>
<Text style={{ fontSize: 20 }}>Decrease</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
function mapStateToProps(state) {
return {
counter: state.counter
}
}
function mapDispatchToProps(dispatch) {
return {
increaseCounter: () => dispatch({ type: 'INCREASE' }),
decreaseCounter: () => dispatch({ type: 'DECREASE' }),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(CounterApp)
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
});

Related

React Native app only works after saving file twice

Basically, a request is made to an API and then the expected result is only presented on the screen after saving the file in vscode twice.
The API is returning the correct result the first time, the problem seems to be linked to useEffect and the updating of the components on the screen, because when I update the desirable result is presented.
I'm saving API data in AsyncStorage and then recovering. I have no idea if I'm doing it right or if there's a better way, but the point is that the app doesn't update the components the first time.
user.js (context)
import React, { createContext, useEffect, useState, useContext } from "react"
import AsyncStorage from "#react-native-async-storage/async-storage"
import ApiRequest from '../services/Api';
const UserContext = createContext({})
export const UserProvider = ({ children }) => {
const [user, setUser] = useState({})
const [services, setServices] = useState([])
useEffect(() => {
let isSubscribed = true;
const getStorage = async (isSubscribed) => {
const storagedToken = await AsyncStorage.getItem('token');
const storagedId = await AsyncStorage.getItem('id');
if(storagedToken && storagedId) {
isSubscribed ? getUser(storagedToken, storagedId) : null;
}
}
getStorage(isSubscribed);
return () => (isSubscribed = false);
}, [])
async function getUser(storagedToken, storagedId) {
try {
const resp = await ApiRequest.getUser(storagedToken, storagedId)
let user = JSON.stringify(resp.Cadastro)
await AsyncStorage.setItem('user', user);
} catch (error) {
console.log('Não foi possível recuperar os dados do usuário, tente novamente.')
}
}
return (
<UserContext.Provider value={{ user, currentService, services, setServiceDate, setServiceType, setCurrentService }}>
{children}
</UserContext.Provider>
)
}
export const useUser = () => {
return useContext(UserContext)
}
Api.js
import axios from 'axios';
import UrlGenerator from './UrlGenerator';
const ApiRequest = {
async getUser(token, id){
try {
const uri = await UrlGenerator.user();
const resp = await axios.post(uri, {
Token: token,
cadastroKey: id
});
return resp.data;
} catch (error) {
//setState(error.toString());
console.log(error);
}
}
}
export default ApiRequest;
WelcomeChamado.js
import React, { useEffect, useState } from 'react'
import { View, Image, ScrollView, StyleSheet, TouchableOpacity } from 'react-native'
import { LinearGradient } from 'expo-linear-gradient';
import { initialWindowMetrics, SafeAreaProvider, useSafeAreaInsets } from 'react-native-safe-area-context';
import NavBar from '../../../components/NavBar';
import { TextMuseo300, TextMuseo500 } from '../../../components/fonts/TextFonts';
import { theme } from '../../../global/theme';
import { TextInputMuseo300 } from '../../../components/fonts/TextInputFonts';
import AsyncStorage from '#react-native-async-storage/async-storage';
const { principalOne, principalTwo, principalThree, destaque, branco } = theme.colors;
import { Entypo } from '#expo/vector-icons';
import loadStoragedUser from '../../../helpers/getUser';
export function WelcomeChamado({ navigation }) {
const insets = useSafeAreaInsets();
const [user, setUser] = useState({});
const [foto, setFoto] = useState('');
useEffect(() => {
async function getUser() {
setUser(await loadStoragedUser());
}
const getInfo = async () => {
const storagedFoto = await AsyncStorage.getItem('#lica:foto');
setFoto(storagedFoto);
}
getInfo();
getUser();
}, []);
const nextScreen = () => {
navigation.navigate("AguardarChamado");
}
return (
<ScrollView
showsVerticalScrollIndicator={false}
contentContainerStyle={{
flexGrow: 1,
}}>
<SafeAreaProvider initialMetrics={initialWindowMetrics}
style={
styles.container,
{
paddingTop: insets.top,
paddingLeft: insets.left,
paddingBottom: insets.bottom,
paddingRight: insets.right,
}
}>
<LinearGradient
start={{ x: 0, y: 0.5 }}
end={{ x: 1, y: 0.5 }}
locations={[0, 0.2, 0.4, 0.6, 0.8, 1]}
colors={['#8EF4F0', '#D6FDFA', '#F8FEFE', '#F8FEFE', '#D6FDFA', '#8EF4F0']}
style={{
flex: 1
}}>
<NavBar navigation={navigation} />
<View style={{
alignItems: 'center',
marginTop: '5%'
}}>
<TextMuseo300 style={{
color: '#2E8F71',
marginTop: '1%',
fontWeight: 'bold',
marginBottom: 10
}}>Olá</TextMuseo300>
<View style={{
justifyContent: 'center',
alignItems: 'center',
}}>
<Image
source={{ uri: `data:image/gif;base64,${foto}` }}
style={{
width: 100,
height: 100,
borderRadius: 50,
borderWidth: 1,
borderColor: destaque,
}}
resizeMode="cover"
/>
<View style={{
position: 'absolute',
top: -5,
right: 0,
backgroundColor: '#2E8F71',
width: 32,
height: 32,
borderRadius: 16,
paddingLeft: 2,
alignItems: 'center',
justifyContent: 'center'
}}>
<Entypo
name="bell"
size={25}
color="#FFF"
/>
</View>
</View>
<TextMuseo300 style={{
color: '#2E8F71',
marginTop: '1%',
fontWeight: 'bold',
marginTop: 10
}}>{user?.CadastroNome}</TextMuseo300>
<TextMuseo300 style={{
color: '#2E8F71',
marginTop: '1%'
}}>{user?.CadastroUser}</TextMuseo300>
</View>
<View style={{
marginTop: 30,
alignItems: 'center',
}}>
<TextMuseo300 style={{
color: '#2E8F71',
marginTop: '2%',
maxWidth: 120,
fontSize: 20,
textAlign: 'center'
}}>Você está disponível para receber chamados?</TextMuseo300>
<TouchableOpacity onPress={nextScreen}>
<View style={{
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#2E8F71',
borderRadius: 10,
width: 120,
height: 30,
marginTop: 50
}}>
<TextMuseo300 style={{
color: '#FFF',
marginTop: '2%',
maxWidth: 120,
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center'
}}>Sim, estou.</TextMuseo300>
</View>
</TouchableOpacity>
</View>
</LinearGradient>
</SafeAreaProvider>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
center: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});

OnPress() using TouchableOpacity is not working in react-native application

When I click the RoundedButton the TouchableOpacity works i.e the opacity of the button reduces but the onPress function doesn't work, the data being passed to the onPress function is correct(as given in the code below). Also, when I tried to console.log("something") inside the onPress function, it doesn't get printed in the console of my terminal.
Here I have the code with function component.
Focus.js file
import React, { useState } from "react";
import { Text, View, StyleSheet } from "react-native";
import { TextInput } from "react-native-paper";
import { RoundedButton } from "../../component/RoundedButton";
export const Focus = ({ addSubject }) => {
const [tmpItem, setTmpItem] = useState();
return (
<View style={styles.container}>
<View style={styles.titleContainer}>
<Text style={styles.title}>What would you like to focus on?</Text>
<View style={styles.inputContainer}>
<TextInput
style={{ flex: 1, marginRight: 20 }}
onSubmitEditing={({ nativeEvent }) => {
setTmpItem(nativeEvent.text);
console.log("tmpItem value set " + tmpItem);
}}
/>
<RoundedButton
size={50}
title="+"
onPress={() => {
console.log("value passed!");
addSubject(tmpItem);
}}
/>
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
titleContainer: {
flex: 0.5,
padding: 10,
justifyContent: "center",
},
title: {
color: "white",
fontWeight: "bold",
fontSize: 21,
},
inputContainer: {
paddingTop: 10,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
},
});
RoundedButton.js File
import React from "react";
import { TouchableOpacity, Text, StyleSheet } from "react-native";
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
...props
}) => {
return (
<TouchableOpacity style={[styles(size).radius, style]}>
<Text style={[styles.text, textStyle]}>{props.title}</Text>
</TouchableOpacity>
);
};
const styles = (size) =>
StyleSheet.create({
radius: {
borderRadius: size / 2,
width: size,
height: size,
alignItems: "center",
justifyContent: "center",
borderColor: "white",
borderWidth: 2,
},
text: {
color: "white",
fontSize: size / 3,
},
});
App.js file
import React, { useState } from "react";
import { Text, View, StyleSheet } from "react-native";
import { Focus } from "./src/features/focus/Focus";
export default function App() {
const [focusSubject, setFocusSubject] = useState(null);
return (
<View style={styles.container}>
{focusSubject ? (
<Text style={{ flex: 1, color: "white", fontSize: 30 }}>
Here is where I am going to build a timer
</Text>
) : (
<Focus addSubject={setFocusSubject} />
)}
<Text style={{ flex: 1, color: "white", fontSize: 30 }}>
{focusSubject}
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 50,
backgroundColor: "#252250",
},
});
you need to extract your onPress props in RoundButton.js and pass to your TouchableOpacity
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
onPress,//<===this
...props
}) => {
return (
<TouchableOpacity onPress={onPress} style={[styles(size).radius, style]}>
<Text style={[styles.text, textStyle]}>{props.title}</Text>
</TouchableOpacity>
);
};
it's seem that you forget to pass onPress function to TouchOpacity
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
onPress,
...props
}) => {
return (
<TouchableOpacity onPress={onPress} style={[styles(size).radius, style]}>
<Text style={[styles.text, textStyle]}>{props.title}</Text>
</TouchableOpacity>
);
};
Now It's Working
Focus.js file
import React, { useState } from "react";
import { Text, View, StyleSheet } from "react-native";
import { TextInput } from "react-native-paper";
import { RoundedButton } from "../../component/RoundedButton";
export const Focus = ({ addSubject }) => {
const [tmpItem, setTmpItem] = useState();
return (
<View style={styles.container}>
<View style={styles.titleContainer}>
<Text style={styles.title}>What would you like to focus on?</Text>
<View style={styles.inputContainer}>
<TextInput
style={{ flex: 1, marginRight: 20 }}
onSubmitEditing={({ nativeEvent }) => {
setTmpItem(nativeEvent.text);
console.log("tmpItem value set " + tmpItem);
}}
/>
<RoundedButton
size={50}
title="+"
onPress={() => {
console.log("value passed!");
addSubject(tmpItem);
}}
/>
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
titleContainer: {
flex: 0.5,
padding: 10,
justifyContent: "center",
},
title: {
color: "white",
fontWeight: "bold",
fontSize: 21,
},
inputContainer: {
paddingTop: 10,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
},
});
RoundedButton.js File
import React from "react";
import { TouchableOpacity, Text, StyleSheet } from "react-native";
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
onPress,
...props
}) => {
return (
<TouchableOpacity onPress={onPress} style={[styles(size).radius, style]}>
<Text style={[styles.text, textStyle]}>{props.title}</Text>
</TouchableOpacity>
);
};
const styles = (size) =>
StyleSheet.create({
radius: {
borderRadius: size / 2,
width: size,
height: size,
alignItems: "center",
justifyContent: "center",
borderColor: "white",
borderWidth: 2,
},
text: {
color: "white",
fontSize: size / 3,
},
});
App.js file
import React, { useState } from "react";
import { Text, View, StyleSheet } from "react-native";
import { Focus } from "./src/features/focus/Focus";
export default function App() {
const [focusSubject, setFocusSubject] = useState();
return (
<View style={styles.container}>
{focusSubject ? (
<Text style={{ flex: 1, color: "white", fontSize: 30 }}>
Here is where I am going to build a timer
</Text>
) : (
<Focus addSubject={setFocusSubject} />
)}
<Text style={{ flex: 1, color: "white", fontSize: 30 }}>
{focusSubject}
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 50,
backgroundColor: "#252250",
},
});

Sending data to another component with (React Native Navigation)

I want to send basic data from Home.js component to details.js component.
My home.js
import React, { useState, useEffect } from 'react'
import { View, TouchableHighlight, Image, FlatList, ActivityIndicator, Text, StyleSheet } from 'react-native'
function HomeScreen({ navigation }) {
const [isLoading, setIsLoading] = useState(true)
const [dataSource, setDataSource] = useState([])
useEffect(() => {
fetch('http://www.json-generator.com/api/json/get/bVxGaxSSgi?indent=2')
.then((response) => response.json())
.then((responseJson) => {
setIsLoading(false)
setDataSource(responseJson)
})
.catch((error) => {
alert(error)
});
})
if (isLoading) {
return (
<View style={{ flex: 1, padding: 20 }}>
<ActivityIndicator />
</View>
)
}
return (
<View style={{ flex: 1, paddingTop: 20, paddingHorizontal: 20 }}>
<FlatList
data={dataSource}
renderItem={({ item }) =>
<TouchableHighlight onPress={() => navigation.navigate('Details',{text:'alperen'})} underlayColor="white">
<View style={styles.button}>
<View style={styles.div}>
<View style={styles.inlineDiv}>
<Image source={{ uri: 'https://source.unsplash.com/random/900&#x2715700/?fruit' }} style={styles.pic} />
<Text>{item.name}, {item.about}</Text>
</View>
</View>
</View>
</TouchableHighlight>
}
keyExtractor={({ _id }, index) => _id}
/>
</View>
)
}
export default HomeScreen
const styles = StyleSheet.create({
pic: {
width: '100%',
height: 200,
borderRadius: 20,
},
div: {
shadowColor: "#fff",
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.20,
shadowRadius: 50,
elevation: 0,
marginBottom: 10
},
inlineDiv: {
padding: 5,
},
button: {
alignItems: 'center',
},
});
This is my details.js component
import React, { useEffect } from 'react'
import { View, Text } from 'react-native'
function DetailsScreen( navigation ) {
useEffect(() => {
alert(navigation.text)
})
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text></Text>
</View>
);
}
export default DetailsScreen
I want to go to the other page and at the same time I want to send and print the data. This code is currently returning undefined. How Can I send data ? Probably I can use props but I don't know usage.
Change
function DetailsScreen( navigation ) {
useEffect(() => {
alert(navigation.text)
})
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text></Text>
</View>
);
}
to
function DetailsScreen({navigation}) {
useEffect(() => {
alert(navigation.state.params.text)
})
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text></Text>
</View>
);
}
And try
In first screen
<TouchableHighlight onPress={() => navigation.navigate('Details',{item})} underlayColor="white">
In next screen you can get data
this.props.navigation.state.params.item
Example:
<Image source={this.props.navigation.state.params.item.img}/>
<Text>{this.props.navigation.state.params.item.text}</Text>
Sending data operation is success but details page is not working. I looked 'react-navigation documentation ' (https://reactnavigation.org/docs/en/params.html). There is a keyword ('route') we have to use it.
function DetailsScreen({ route }) {
const { text } = route.params;
useEffect(() => {
var a = JSON.stringify(text)
alert(a)
})
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text></Text>
</View>
);
}
I tried this code and its working success.

A problem with a trivial react native code with hooks

Update:
Problem 2. is solved (thanks to #NikolayNovikov reply) by replacing "setResources({ resources: response.data })" with
"setResources(response.data)".
Problem 1. I cannot reproduce it...
Description of the problem:
The following trivial example is fetching data from jsonplaceholder.typicode.com, and, since there are 100 'posts' and 200 'todos', it is supposed to display 100 and 200 when you click on these buttons.
For some reason that I cannot find (embarrassing, I know...), there are two problems:
When I click on the 'posts' button, useEffect is called twice (once with 'todos' and once with 'posts', and when I click on the 'todos' button it is not called at all.
resource.length is not rendered
Any idea what is wrong?
App.js:
import React, { useState } from 'react';
import { View, TouchableOpacity, Text, StyleSheet } from 'react-native';
import { ResourceList } from './components/ResourceList';
console.warn('In App.js: Disabling yellowbox warning in genymotion');
console.disableYellowBox = true;
export const App = () => {
const [resource, setResource] = useState('todos');
return (
<View style={{ flex: 1, alignItems: 'center', marginTop: 100 }}>
<Text style={{ fontSize: 20, fontWeight: '500' }}>
The Application has been loaded!
</Text>
<View style={{ flexDirection: 'row', marginTop: 100,
alignItems: 'center', justifyContent: 'center' }}>
<TouchableOpacity onPress={() => setResource('posts')}>
<View style={styles.button}>
<Text style={styles.buttonText}>
Posts
</Text>
</View>
</TouchableOpacity>
<View style={{ width: 20 }} />
<TouchableOpacity onPress={() => setResource('todos')}>
<View style={styles.button}>
<Text style={styles.buttonText}>
Todos
</Text>
</View>
</TouchableOpacity>
</View>
<ResourceList resource={resource} />
</View>
);
}
const styles = StyleSheet.create({
buttonText: {
color: 'black',
fontSize: 20
},
button: {
backgroundColor: '#a8a',
justifyContent: 'center',
alignItems: 'center',
paddingVertical: 5,
paddingHorizontal: 10,
borderRadius: 2
}
});
ResourceList.js:
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';
// export const ResourceList = (props) => {
export const ResourceList = ({ resource }) => { // restructured props
const [resources, setResources ] = useState([]);
const fetchResource = async(resource) => {
console.log('+++ ResourceList/fetchResource calling axios. path:',
`https://jsonplaceholder.typicode.com/${resource}`);
const response = await axios.get(`https://jsonplaceholder.typicode.com/${resource}`);
console.log(response);
setResources({ resources: response.data })
}
useEffect(() => {
console.log('--- ResourceList/useEffect. resource: ', resource);
fetchResource(resource);
}, [resource]);
return (
<View style={{ flex: 1, alignItems: 'center', marginTop: 100 }}>
<Text style={{ fontSize: 20, fontWeight: '500' }}>
{resources.length}
</Text>
</View>
);
}
In you ResourceList.js component setResources should be different, please try this:
setResources(response.data)

React-native function not returning get data

I see just "t pera" but not gotten name from getStudentName function before "t pera".
import React, { Component } from 'react';
import {
Alert,
AppRegistry,
StyleSheet,
Text,
Navigator,
TextInput,
View,
Platform,
TouchableHighlight,
TouchableNativeFeedback,
} from 'react-native';
export class Student extends Component {
getStudentName() {
return fetch('http://192.168.1.14:3005/api/users/57bf7c101a7c1a892f6a19bc')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.name;
})
.catch((error) => {
console.error(error);
})
}
onButtonPress(){
this.props.navigator.push({
id: 'Student'
})
}
render() {
return(
<View style={styles.container}>
<TextInput style={styles.input}
placeholder = "peki"
/>
<Text>
{this.getStudentName}t pera
</Text>
<TouchableHighlight style={styles.button1} onPress={this.getStudentName}>
<Text style={styles.nastavi}>Nastavi</Text>
</TouchableHighlight>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FFFFFF',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
padding: 30
},
input: {
borderBottomColor: 'grey',
borderBottomWidth: 1,
height: 40,
width: 250
},
button1: {
height: 40,
borderRadius: 5,
backgroundColor: '#4a4de7',
width: 250,
marginTop: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
button2: {
height: 40,
borderRadius: 5,
backgroundColor: 'black',
width: 250,
marginTop: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
nastavi: {
color: 'white',
fontSize: 15
}
});
module.exports = Student;
It's because your getStudentName() method isn't returning the string you're expecting, but a promise. You should update the state of your component from the result, rather than returning anything.
Notice below that I've replaced "this.getStudentName" with this.state.studentName, which will return an empty string (as defined in the constructor) until the promise from your method getStudentName() updates the state. Once the promise is finished and the state updates, it'll automatically refresh your views to show the student name.
export class Student extends Component {
constructor(props) {
super(props);
this.state = {
studentName: ''
};
}
componentDidMount() {
this.getStudentName();
}
getStudentName() {
var self = this;
return fetch('http://192.168.1.14:3005/api/users/57bf7c101a7c1a892f6a19bc')
.then((response) => response.json())
.then((responseJson) => {
self.setState({
studentName: responseJson.name
});
})
.catch((error) => {
console.error(error);
});
}
onButtonPress(){
this.props.navigator.push({
id: 'Student'
})
}
render() {
return(
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder = "peki" />
<Text>
{this.state.studentName}t pera
</Text>
<TouchableHighlight style={styles.button1} onPress={this.getStudentName.bind(this)}>
<Text style={styles.nastavi}>Nastavi</Text>
</TouchableHighlight>
</View>
);
}