Using an API response to trigger a modal - reactjs

I'm attempting to use the response from my API (the response being a number ranging from -3 to +3) to trigger a modal. I receive a response from the API and store the number in a state var setModalVisible which I thought would cause the modal to appear however it does not. Eventually I would like varying modals to appear dependent upon the number, i.e if (response < 3) { certainModal } else { } however I can't get this initial one to render.
Below is a snippet containing the most relevant code:
async function makePostRequest (diaryText) {
let payload = { description: diaryText };
let response = await axios.post('http://localhost:3000/', payload);
let data = response.data.replace(/[^0-9+\/*=\-.\s]+/g, '');
return data;
}
makePostRequest(diaryText)
.then(response => {
this.setState({ setModalVisible: response });
})
.catch(error => {
error.message;
})
const [modalVisible, setModalVisible] = useState(false);
return (
<View style={styles.centeredView}>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Manderley thinks you are feeling good/okay/bad, is this correct?</Text>
<Pressable
style={[styles.YesButton, styles.YesButtonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={styles.textStyle}>Yes</Text>
</Pressable>
<Pressable
style={[styles.NoButton, styles.NoButtonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={styles.textStyle}>No</Text>
</Pressable>
</View>
</View>
</Modal>
</View>
)

I think the idea is you just need to check the value after you get the API response.
Let's say you have a function:
function checkAPIValue() {
const apiResponse = functionToCallAPI()
if (apiResponse.response < 3){
setModalVisible(true) // Here you change the value of your modalVisible
}
}

Related

react_native + iframe + firebase : How could I serve the videoId of next index from realtime database?

now i use react native, expo project.
and i apply realtime database, iframe, FlatList.
and i use videoID instead of the 'scr= URL'.
i hope to autoplay by auto changing the videoId in my realtime database.
i think it can be possible by using index number.
and when i console.log selected index, it presented on terminal.
but i don't know how to apply that path for my code.
this is my realtime database.
enter image description here
and this is my codes.
import YoutubePlayer from "react-native-youtube-iframe";
const [state, setState] = useState([])
const [cardID, setCardID] = useState(["i4S5hvPG9ZY"])
const [playing, setPlaying] = useState(true);
const onStateChange = useCallback((state) => {
if (state === "ended") {
setPlaying(true)
}
}, []);
const onPress = ({ item, index }) => {
console.log({ index })
return (
setCardID(item.id.videoId)
)
}
...
useEffect(() => {
setLoading(true);
firebase_db.ref('/TGBSitems')
.once('value')
.then((snapshot) => {
console.log("TGBS에서 데이터 가져왔습니다!!")
let TGBSitems = snapshot.val()
setState(TGBSitems)
setTotalDataSource(TGBSitems);
setLoading(false);
})
.catch(err => { setLoading(false); setError(err); })
}, []);
...
return (
...
<View>
<YoutubePlayer
height={200}
play={playing}
videoId={cardID}
onChangeState={onStateChange}
// playList
/>
</View>
...
<FlatList
data={state}
// ItemSeparatorComponent={ItemSeparatorView}
keyExtractor={(index) => index.toString()}
renderItem={({ item, index }) => (
<View style={styles.cardContainer}>
<TouchableOpacity style={styles.card} onPress={() => onPress({ item, index })}>
<Image style={styles.cardImage} source={{ uri: item.snippet.thumbnails.medium.url }} />
<View style={styles.cardText}>
<Text style={styles.cardTitle} numberOfLines={1}>{item.snippet.title}</Text>
<Text style={styles.cardDesc} numberOfLines={3}>{item.snippet.description}</Text>
<Text style={styles.cardDate}>{item.snippet.publishedAt}</Text>
<Text style={styles.cardDate}>{item.id.videoId}</Text>
<Text style={styles.cardDate}>{index}</Text>
</View>
...

State does not update its value using AsyncStorage in react-native

I am trying to save a value to async storage and then navigate to the right page depending on what the value outcome is from the Async storage. I can store data in AsyncStorage but my states does not update, I have to reload the app in order for the state to update. here is my code:
Here I have a Welcome/Obnoarding screen. I want this screen to only show to the new app users. So when a user presses the continue button I want to save a value to the Async storage so that the next time they log in they don't have to see the onboarding page again. Here is my Onboarding page:
const WelcomeScreen: FC<IWelcomeScreen> = ({ navigation }) => {
const { width, height } = Dimensions.get("window");
const btnText = "Contiunue";
const title = "Book";
const subTitle = "Fab";
let [fontsLoaded] = useFonts({
PinyonScript_400Regular,
});
const continueBtn = async () => {
try {
await AsyncStorage.setItem('#viewedOnboarding', 'true');
} catch (error) {
console.log('Error #setItem: ', error);
};
};
if (!fontsLoaded) {
return <Text>...Loading</Text>;
} else {
return (
<View style={containerStyle(height, width).container}>
<ImageBackground
resizeMode={"cover"}
style={styles.image}
source={require("../assets/model.jpg")}
>
<LinearGradient
colors={["#00000000", "#000000"]}
style={styles.gradient}
>
<View style={styles.container}>
<View style={styles.logoTextContainer}>
<Text style={styles.logoText}>{title}</Text>
<Text style={styles.logoText}>{subTitle}</Text>
</View>
<ContinueBtn label={btnText} callback={continueBtn} />
</View>
</LinearGradient>
</ImageBackground>
</View>
);
}
};
In my AppNavigator I want to decide which navigation the user should see. But when I press the continue page my app does not navigate to my TabsNavigator. It stays on my Onboarding page but if I refresh the app then the app navigates to my Tabs navigator. here is the code where I determine where the user should be depending if they are a new user or a "old" user:
const WelcomeScreen: FC<IWelcomeScreen> = ({ navigation }) => {
const { width, height } = Dimensions.get("window");
const btnText = "Contiunue";
const title = "Book";
const subTitle = "Fab";
let [fontsLoaded] = useFonts({
PinyonScript_400Regular,
});
const continueBtn = async () => {
try {
await AsyncStorage.setItem('#viewedOnboarding', 'true');
} catch (error) {
console.log('Error #setItem: ', error);
};
};
if (!fontsLoaded) {
return <Text>...Loading</Text>;
} else {
return (
<View style={containerStyle(height, width).container}>
<ImageBackground
resizeMode={"cover"}
style={styles.image}
source={require("../assets/model.jpg")}
>
<LinearGradient
colors={["#00000000", "#000000"]}
style={styles.gradient}
>
<View style={styles.container}>
<View style={styles.logoTextContainer}>
<Text style={styles.logoText}>{title}</Text>
<Text style={styles.logoText}>{subTitle}</Text>
</View>
<ContinueBtn label={btnText} callback={continueBtn} />
</View>
</LinearGradient>
</ImageBackground>
</View>
);
}
};
Setting a value in the async storage will not trigger a rerender of your AppNavigator. Thus, if the user presses the continue button, then nothing will happen visually, since the state of AppNavigator has not changed. If you refresh the app, the flag, which you have set previously using the setItem function, will be reloaded in AppNavigator on initial rendering. This is the reason why it works after refreshing the application.
For this kind of problem, I would suggest that you use a Context for triggering a state change in AppNavigator.
Here is a minimal example on how this would work. I have added comments in the code to guide you.
For the sake of simplicity, we will make the following assumption:
We have two screens in a Stack, one is the WelcomeScreen, the other one is called HomeScreen.
Notice that we use conditional rendering for the screens depending on our application context. You can add whatever screens you want, even whole navigators (this would be necessary if your navigators are nested, but the pattern stays the same).
App
export const AppContext = React.createContext()
const App = () => {
// it is important that the initial state is undefined, since
// we need to wait for the async storage to return its value
// before rendering anything
const [hasViewedOnboarding, setHasViewedOnboarding] = React.useState()
const appContextValue = useMemo(
() => ({
hasViewedOnboarding,
setHasViewedOnboarding,
}),
[hasViewedOnboarding]
)
// retrieve the onboarding flag from the async storage in a useEffect
React.useEffect(() => {
const init = async () => {
const value = await AsyncStorage.getItem('#viewedOnboarding')
setHasViewedOnboarding(value != null ? JSON.parse(value) : false)
}
init()
}, [])
// as long as the flag has not been loaded, return null
if (hasViewedOnboarding === undefined) {
return null
}
// wrap everything in AppContext.Provider an pass the context as a value
return (
<AppContext.Provider value={appContextValue}>
<NavigationContainer>
<Stack.Navigator>
{!hasViewedOnboarding ? (
<Stack.Screen name="Welcome" component={WelcomeScreen} />
) : (
<Stack.Screen
name="Home"
component={HomeScreen}
/>
)}}
</Stack.Navigator>
</NavigationContainer>
</AppContext.Provider>
)
}
Now, in your WelcomeScreen you need to access the context and set the state after the async value has been stored.
const WelcomeScreen: FC<IWelcomeScreen> = ({ navigation }) => {
// access the context
const { setHasViewedOnboarding } = useContext(AppContext)
const { width, height } = Dimensions.get("window");
const btnText = "Contiunue";
const title = "Book";
const subTitle = "Fab";
let [fontsLoaded] = useFonts({
PinyonScript_400Regular,
});
const continueBtn = async () => {
try {
await AsyncStorage.setItem('#viewedOnboarding', 'true');
setHasViewedOnboarding(true)
} catch (error) {
console.log('Error #setItem: ', error);
};
};
if (!fontsLoaded) {
return <Text>...Loading</Text>;
} else {
return (
<View style={containerStyle(height, width).container}>
<ImageBackground
resizeMode={"cover"}
style={styles.image}
source={require("../assets/model.jpg")}
>
<LinearGradient
colors={["#00000000", "#000000"]}
style={styles.gradient}
>
<View style={styles.container}>
<View style={styles.logoTextContainer}>
<Text style={styles.logoText}>{title}</Text>
<Text style={styles.logoText}>{subTitle}</Text>
</View>
<ContinueBtn label={btnText} callback={continueBtn} />
</View>
</LinearGradient>
</ImageBackground>
</View>
);
}
};

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'currentUser.uid')]

i get this warning when i try to store details to firebase using the currently logged in user.
i followed a online tutorial but i get this problem, is there any alternate method to use to achieve this?
i read about this problem but couldn't find a fix, i saw that its due to the user not being logged in but i did log in
var currentUser
class DecodeScreen extends Component {
addToBorrow = async (booktitle, bookauthor, bookpublisher, bookisbn) => {
currentUser = await firebase.auth().currentUser
var databaseRef = await firebase.database().ref(currentUser.uid).child('BorrowedBooks').push()
databaseRef.set({
'title': booktitle,
'author': bookauthor,
'publisher': bookpublisher,
'isbn': bookisbn
})
}
state = {
data: this.props.navigation.getParam("data", "NO-QR"),
bookData: '',
bookFound: false
}
_isMounted = false
bookSearch = () => {
query = `https://librarydb-19b20.firebaseio.com/books/${9781899606047}.json`,
axios.get(query)
.then((response) => {
const data = response.data ? response.data : false
console.log(data)
if (this._isMounted){
this.setState({ bookData: data, bookFound: true })
}
})
}
renderContent = () => {
if (this.state.bookFound) {
return(
<View style={styles.container2}>
<View style={styles.htext}>
<TextH3>Title :</TextH3>
<TextH4>{this.state.bookData.title}</TextH4>
</View>
<View style={styles.htext}>
<TextH3>Author :</TextH3>
<TextH4>{this.state.bookData.author}</TextH4>
</View>
<View style={styles.htext}>
<TextH3>Publisher :</TextH3>
<TextH4>{this.state.bookData.publisher}</TextH4>
</View>
<View style={styles.htext}>
<TextH3>Isbn :</TextH3>
<TextH4>{this.state.bookData.isbn}</TextH4>
</View>
</View>
)
}
else {
return(
<View style={styles.loading}>
<ActivityIndicator color="blue" size="large" />
</View>
)
}
}
componentDidMount(){
this._isMounted = true
}
componentWillUnmount(){
this._isMounted = false
}
render() {
{this.bookSearch()}
return (
<View style={styles.container}>
{this.renderContent()}
<Button title='Borrow' onPress={() => this.addToBorrow(this.state.bookData.title, this.state.bookData.author, this.state.bookData.publisher, this.state.bookData.isbn)} />
</View>
);
}
}
First, firebase.auth().currentUser is not a promise, and you can't await it. It's either null or a user object.
Second, it's not guaranteed to be populated with a user object on immediate page load. You will need to use an auth state observer to know when the user object first becomes available after a page load.

"Can only update a mounted or mounting component" warning comes up while using a setInterval

I am developing an App with React Native. I need to retrieve some data using fetch every 30 seconds. My code works fine and it retrieves the data correctly every 30 seconds. My problem is that as soon as I redirect to another screen, I get the following warning:
Warning: Can only update a mounted or mounting component. This usually
means you called setState() on an unmounted component. This is a
no-op. Please check the code for the xxxxxxxxx component.
Here is my code:
dataGet() {
listColumnFetch(this).then(result => {
let ColumnData = result.list;
let ColumnDataArray = Object.keys(ColumnData).map((key) => { return ColumnData[key] });
console.log("serverDataArray:", this.ColumnDataArray);
this.setState({
ColumnData,
ColumnDataArray,
isLoading: false,
CurrentData: new Date(),
});
});
}
componentDidMount() {
this.dataGet();
this.interval = setInterval(() => this.dataGet(), 30000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
Although I did clearInterval in componentWillUnmount, the App gives me that warning every 30 seconds in other pages. It seems that the timer didn't stop and it is in background. Can you help me to solve this problem?
UPDATE:
Also here I try to redirect to another page. Here is the rest of my code:
onPressNew() {
this.props.navigation.navigate('RechargeElectricCar', {user: this.state.user, activeSection: 'NoChargeInProgress_2a'});
}
render() {
if (this.state.isLoading) {
return(
<View>
<ActivityIndicator size="large" color="#79b729"/>
</View>
);
}
return (
<View style={styles.container} ref="park-progress-ref">
<View style={styles.titleContainer}>
<Text style={styles.itemBold}>{I18n.t('queste_ricariche')}</Text>
</View>
<View style={ styles.rowSep } />
<View style={ styles.listContainer } >
<FlatList
ItemSeparatorComponent={ () => <View style={ styles.rowSep } /> }
horizontal={false}
data={this.state.result}
renderItem={
({item}) => (
<View style={styles.containerrow}>
<View style={styles.viewPark}>
<Text style={styles.itemBold}> {I18n.t('Data_e_ora_inizio')}: <Text style={styles.itemNormal}>{item.start}</Text></Text>
<Text style={styles.itemBold}> {I18n.t('Data_e_ora_termine')}: <Text style={styles.itemNormal}>{item.end}</Text></Text>
<Text style={styles.itemBold}> {I18n.t('Energia')}: <Text style={styles.itemNormal}>{item.energy_delivered} KWh</Text></Text>
<Text style={styles.itemBold}> {I18n.t('Colonna')}: <Text style={styles.itemNormal}>{item.column_id}</Text></Text>
<Text style={styles.itemBold}> {I18n.t('Costo_della_ricarica')}: <Text style={styles.itemNormal}>€ {item.amount}</Text></Text>
<Text style={styles.itemBold}> {I18n.t('Aggiornamento_del')}: <Text style={styles.itemNormal}>{this.currentTime()}</Text></Text>
</View>
<View style={styles.rowCenter}>
<Button label={I18n.t('Via_questa_ricarica')} color={defStyleValues.RechargeElectricCar} onPress={ () => {console.log("MARCO log"); this.onPressTopUp(item.column_id)} } />
</View>
</View>
)
}
keyExtractor={item => item.id}
/>
</View>
<View style={ styles.rowSep } />
<View style={ styles.buttonContainer } >
<FadeInView
duration={2000}
style={{ alignItems: 'center' }}>
<ButtonIcon_White onPress={ () => { this.onPressNew() }} label={I18n.t('Nuova_ricarica')} />
</FadeInView>
</View>
</View>
);
}
When you navigate to a new screen, the new screen will be pushed on top of the previous screen. Because of this the previous screen will not be unmounted. This is why your interval is not clearing.
What you can do is to set a variable or a state value before doing a redirection and then checking the value before doing another setState.
Another thing to consider is to changing the value when you come back to previous screen. To handle that you can pass a function as a parameter to next screen and run it when the next screen's componentWillUnmount like below.
Example
onPressNew() {
// set stop value before navigating
this.setState({ stop: true }, () => {
this.props.navigation.navigate('RechargeElectricCar', {
user: this.state.user,
activeSection: 'NoChargeInProgress_2a',
onBack: this.onBack // Added this param for changing state to false
});
});
}
onBack = () => {
this.setState({stop: false});
}
//....
dataGet() {
// check stop value before fetching
if(this.state.stop !== true) {
listColumnFetch(this).then(result => {
let ColumnData = result.list;
let ColumnDataArray = Object.keys(ColumnData).map((key) => { return ColumnData[key] });
console.log("serverDataArray:", this.ColumnDataArray);
this.setState({
ColumnData,
ColumnDataArray,
isLoading: false,
CurrentData: new Date(),
});
});
}
}
On next screen (RechargeElectricCar screen)
componentWillUnmount() {
this.props.navigation.state.params.onBack()
}
Problem is with your setState setting state when your component has unmounted.
componentDidMount() {
this.isMountedComp = true
}
dataGet() {
listColumnFetch(this).then(result => {
let ColumnData = result.list;
let ColumnDataArray = Object.keys(ColumnData).map((key) => { return ColumnData[key] });
console.log("serverDataArray:", this.ColumnDataArray);
if(this.isMountedComp) {
this.setState({
ColumnData,
ColumnDataArray,
isLoading: false,
CurrentData: new Date(),
});
});
}
}
componentWillUnMount() {
clearInterval(this.interval);
this.isMountedComp = false
}
This will remove the warning errors.

setState when fetch data that leads Render in loop

The problem is when i create paginaion button, the render is running in loop.
As i call api from external that i can store all data in dataset. I know something went wrong but i am not able to solve it personally, so can any one suggest solutions to help improve? Thanks.
SearchScreen.js
componentDidMount() {
this.setState({isLoading: true},function(){
this.fetchData(this.url)
});
}
async fetchData(query, pageNo) {
try {
let response = await fetch(query);
let responseText = await response.json();
let json = await this.getData(responseText, pageNo);
} catch(error) {
console.error(error);
}
}
async getData(responseText, pageNo){
this.setState({
data: responseText.response.listings,
isLoading: false,
currentPage: pageNo,
lastPage: responseText.response.total_pages
});
}
PropertyList(arr, navigate) {
return arr.map(function(property, i){
return(
<TouchableHighlight style={styles.button} underlayColor='#99d9f4'
key={i} onPress={() => navigate('PropertyView', {property: property})} >
<View key={i} style={styles.rowContainer}>
<Image style={styles.thumb} source={{ uri: property.img_url }} />
<View style={styles.textContainer}>
<Text style={styles.price}>{property.price_formatted}</Text>
<Text style={styles.title}
numberOfLines={2}>{property.title}</Text>
</View>
</View>
</TouchableHighlight>
);
});
}
SetPage = (pageNo) =>{
this.url = this.GetChangedUrl(pageNo);
this.fetchData(this.url, pageNo);
}
GetChangedUrl = (pageNo) =>{
return this.url.replace(/(page=\d+&)/g, 'page='+pageNo+ '&');
}
_formArray = (pageNo) =>{
if (pageNo == 1){
return [pageNo, pageNo+1, pageNo+2];
}else if (pageNo == this.lastPage){
return [pageNo-2, pageNo-1, pageNo];
}else{
return [pageNo-1, pageNo, pageNo+1];
}
}
_createPageButton = (currentPage) =>{
var array = this._formArray(currentPage);
var btnBody = array.map( (item, i) => {
return (
<TouchableHighlight style={styles.pageButton} key={i} Onpress={this.SetPage(i)}>
<Text style={styles.text} >{i + 1}</Text>
</TouchableHighlight>
)
});
return btnBody;
}
render() {
const { navigate } = this.props.navigation;
const { params } = this.props.navigation.state;
this.url = params.url;
let propertyList;
if (this.state.isLoading){
propertyList = (
<ActivityIndicator size={108} style= {styles.indicator}/>
)
}else{
propertyList = (
<View >
<View >
<ScrollView >
{this.PropertyList(this.state.data, navigate)}
<View style={styles.separator}/>
<View style={styles.pageContainer}>
{this._createPageButton(this.currentPage)}
</View>
</ScrollView>
</View>
</View>
)
}
return (
<View>
{propertyList}
</View>
)
}
}
Whole Code from here
I believe this is caused by:
Onpress={this.SetPage(i)}
which should be changed to:
Onpress={() => this.SetPage(i)}
Your code calls setPage when rendering and passes to onPress the result of the call, causing change of page, and therefore a new load, on every render.

Resources