Hi everyone i am new to react-native. I'm trying to make a network request, save the result, and pass the result into the main App.js class
import { Component } from "react";
class Utils extends Component{
constructor(props) {
super(props);
this.state = {
data: " ",
};
}
getSid(){
try {
fetch('https://help_me').
then((response) =>response.json()).then((responseJson)=>{
this.setState({ data: responseJson.sid });
});
} catch (error) {
console.log(error);
}
}
}
const utils = new Utils();
export default utils;
Now App.js:
import React, { Component } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
import utils from './Utils';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: " ",
};
}
componentDidMount() {
utils.getSid()
}
render() {
const { data} = this.state;
return (
<View style={{ flex: 1, padding: 24 }}>
<Text>{utils.state.data}</Text>
</View>
);
}
};
when I try to start the app, the device shows me a blank screen. because? then every time I create a new component (for example Utils.js) do I always have to specify its state? thanks a lot to everyone.
CodePudding user response:
Just one question, why not like this ? rather than Util class, directly in your comp?
import React, { Component } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
import utils from './Utils';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: " ",
};
}
getSid(){
try {
fetch('https://help_me').
then((response) =>response.json()).then((responseJson)=>{
this.setState({ data: responseJson.sid });
});
} catch (error) {
console.log(error);
}
}
componentDidMount() {
getSid()
}
render() {
const { data} = this.state;
return (
<View style={{ flex: 1, padding: 24 }}>
<Text>{data}</Text>
</View>
);
}
};
or why not a normal util function rather than class :
export const getSid = () => {
try {
fetch('https://help_me').
then((response) =>response.json()).then((responseJson)=>{
return responseJson
});
} catch (error) {
console.log(error);
}
}