how to access particular data in api call response in react native - javascript

I am using react native and working with the moviesDB API.For some reason, I cannot access the data I am looking for in the response of the api call. I am trying to get the "poster_path" info from the api call. So in my console.log, If call this.state.movies, I see the data of many movies there as well as the "poster_path" key that I want to access and its info. However, when I console.log this.state.movies.poster_path, it shows undefined. Just wondering why its doing that. I have tried searching online for answers and also tried to wrap brackets and take out the spread operator. Please see below for code and picture of console. Thanks!
import { View, Text, StyleSheet, TextInput, Image } from "react-native";
import { FlatList, TouchableOpacity } from "react-native-gesture-handler";
import MovieItem from "../components/MovieItem";
const API_KEY2="*******";
class SearchScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
movies: \[\],
searchTerm: "",
}
}
handleSubmit =(e)=> {
fetch(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY2}&query=${this.state.searchTerm}`)
.then(data => data.json())
.then(data=> {
this.setState({
movies: \[...data.results\]
});
console.log("RESPONSE FROM THIS.STATE.MOVIES", this.state.movies)
console.log("RESPONSE FROM THIS.STATE.MOVIES.POSTER_PATH",this.state.movies.poster_path)
})
}
handleChange=(textToSearch)=> {
this.setState({
searchTerm: textToSearch
});
}
render() {
return(
<View style={styles.screen}>
<TextInput
style={styles.input}
onSubmitEditing={this.handleSubmit}
onChangeText={(text)=>this.handleChange(text)}
placeholder="Enter Movie"
/>
<FlatList
data={this.state.movies}
renderItem={({item})=> {
return(
<TouchableOpacity onPress={()=> this.props.navigation.navigate("MovieItem", {item})}>
<View style={styles.movieItem}>
<Image source={{uri:`https://image.tmdb.org/t/p/w1280/${item.poster_path}`}}
style={{
height: 220,
width: 200
}}/>
<MovieItem item={item}/>
</View>
</TouchableOpacity>
)
}} />
</View>
)
}
}
const styles = StyleSheet.create({
screen: {
flex: 1,
backgroundColor:"tomato",
justifyContent:"center",
alignItems:"center",
flexDirection:"column"
},
input: {
borderStyle:"solid",
borderWidth: 5,
width:"100%",
padding: 20,
backgroundColor:"white",
fontFamily:"Yesteryear-Regular",
fontSize: 20,
color:"tomato"
},
movieItem: {
marginTop: 20,
marginBottom: 20
},
})
export default SearchScreen;][1]][1]
// response for this.state.movies
// response for this.state.movies.poster_path

var temp = [{'poster_path' :'xxx'}];
temp[0].poster_path;

Related

ScrollView in React Native

I created a simple app, that shows a few pictures with titles. It is something like a film gallery, where you can observe all enable films. But when I try to add ScrollView element it doesn't work when I try to scroll on my emulated Android device. How can I fix it? My code looks like this:
import React, { Component } from 'react'
import { View, ScrollView, StyleSheet } from 'react-native'
import { Header, ImageCard } from './src/components/uikit'
const url = 'https://s3.eu-central-1.wasabisys.com/ghashtag/RNForKids/00-Init/data.json'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
title: 'STAR GATE',
data: []
};
}
componentDidMount = async () => {
try {
const response = await fetch(url)
const data = await response.json()
this.setState({ data })
}
catch (e) {
console.log(e)
throw e
}
}
render() {
const { title, data } = this.state
const { container } = style
return (
<View>
<Header title={title} />
<ScrollView>
<View style={container}>
{
data.map(item => {
return <ImageCard data={item} key={item.id} />
})
}
</View>
</ScrollView>
</View>
)
}
}
const style = StyleSheet.create({
container: {
marginTop: 30,
flexDirection: 'row',
flexWrap: 'wrap',
flexShrink: 2,
justifyContent: 'space-around',
marginBottom: 150
}
})
I made it with a guide, so it should work. (Youtubes author hasn't this problem on his video).
The View inside ScrollView looks problematic. Try something like:
<ScrollView contentContainerStyle={container} >
{
data.map(item => {
return <ImageCard data={item} key={item.id} />
})
}
</ScrollView>

RefreshControll data duplicate everytime do pull to refresh on ScrollView in React native

Description
I implement a pull request using RequestController in React Native, every time I did pull to refresh the same data keep adding on in Flat list over and over. I implemented pull request not inside the Flat list but on the ScrollView which wrapped the FlatList.
Actions
import React, { Component } from 'react';
import { View, StyleSheet, Text, Button, Modal, Dimensions, ScrollView, TextInput, TouchableOpacity, StatusBar, Image, Platform, TouchableNativeFeedback,FlatList, ImageBackground, RefreshControl } from 'react-native';
import axios from 'axios';
class HomeScreen extends Component{
state = {
refreshing: false,
}
componentDidMount(){
this.searchApi();
}
searchApi = async() => {
const response = await axios.get('http://73udkYid.ngrok.io/api/v1/products',{
headers: {
"x-auth-token":"eyJfaWQiOiI1ZdfjzZmM4YjIwYjBjZDQyMmJkNzUiLCJpYXQiOjE2MD"
}
}
);
this.setState({results: [...this.state.results, response.data]});
}
_onRefresh = () => {
this.setState({refreshing: true});
this.searchApi().then(() => {
this.setState({refreshing: false});
});
}
render(){
let finalGames = [];
this.state.results.forEach(obj => {
Object.keys(obj).forEach(key => {
finalGames.push(obj[key]);
});
});
return (
<ScrollView style={{flex: 1,backgroundColor: 'white',}}
refreshControl = {
<RefreshControl
refreshing = { this.state.refreshing }
onRefresh={this._onRefresh}
/>
}
>
<FlatList
data = { finalGames }
keyExtractor = {(item, index) => index.toString()}
renderItem = { ({item: itemData}) => {
if(itemData.empty == true){
return <View style = {[styles.item,styles.itemInvisible]}/>
}
return (
<View style = {{ flex: 1, margin: 4}}>
<View style = {styles.item}>
<TouchableOpacity
onPress = {() => {
this.setState({ viewController: this.state.viewController++ })
this.props.navigation.navigate(
"ProductDetail", {
itemDataDetail: itemData,
businessname:this.props.navigation.state.params.businessname,
viewController: this.state.viewController,
})
}}>
<View>
<ImageBackground
source={{ uri: itemData.photo }}
style={{ width:'100%',aspectRatio: 1, borderRadius: 15, borderWidth:1, borderColor:"#FAFAFA", overflow: 'hidden'}}>
</ImageBackground>
<View style = {{ margin: 5}}>
<Text style = {{color: '#2E2E2E', fontWeight:"bold"}} numberOfLines={1}>{itemData.item}</Text>
<Text style = {{color: '#2E2E2E', fontSize: 12, fontWeight:"normal", alignSelf: 'flex-start'}} numberOfLines={1}>Available now | Sold out</Text>
<Text style = {{color: 'white', fontSize: 18, fontWeight:"bold", backgroundColor:"#DE1F38", alignSelf: 'flex-start', paddingHorizontal: 10,paddingVertical:2,borderRadius: 8,overflow: 'hidden', marginTop: 5}} numberOfLines={1}>${itemData.price}</Text>
</View>
</View>
</TouchableOpacity>
</View>
</View>
</ScrollView>
);
}}/>
}
Output
Data duplicated every time new pull refresh triggered
I assume your api-call returns the whole list of products
This line concat api-response-data to the the list of products you already have in your component-state
this.setState({results: [...this.state.results, response.data]});
Try this instead...
this.setState({ results: response.data });
You should replace your data instead of concatenating. Use:
this.setState({ results: response.data });
Also, you should use FlatList 'onRefresh' prop to implement refresh functionality instead of using an extra ScrollView on the parent.
Oh I found a way. I just need to do this.
this.setState({results: [response.data]});
I was facing the same problem as you,
When I refreshed, the data was (data)+[(data)+(new_data)].
What happens here is that data is added to the array of this variable: results.
To prevent this you must first clear this variable: results.
So your code will look like this.
state = {
refreshing: false,
results : [],
}
when API runs, this array will filled results[{some_data},{some_data},{some_data},..],
While you refresh->
1st: The results will Empty,
2nd: reassign that array with newly added data from API.
_onRefresh = () => {
this.setState({results: []});
this.setState({refreshing: true});
this.searchApi().then(() => {
this.setState({refreshing: false});
});
}

React Native: Json not showing in Screen: Getting Error in Console

I am getting this error when trying to bring JSON data from mongodb into screen of React Native Application. Screen is showing, just no data. Error is below with code. This is simple hello world app and I am trying to bring in some json data from mongodb to the screen. I am just not sure of the correct setup, though I do have the screen visible up to choose your listing in Listings.js file. for some reason the network is not working. Not sure if I need to proxy in package.json?
App.js
import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {Listings} from './src/Listings';
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={{flex: 1}}>
<Text style={styles.welcome}>Air BNB Data Screen</Text>
<View style={{flex: 1, borderWidth: 3, borderColor: 'blue'}}>
<Listings></Listings>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
src
Listings.js
import React from 'react';
import {StyleSheet, View, FlatList, Text} from 'react-native';
import axios from 'axios';
export class Listings extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
show: true,
};
}
componentDidMount = () => {
const options = {
headers: {'Content-Type': 'application/json'},
};
axios
.get('http://localhost:8080/api/Listings/10006546', options)
.then((response) => {
this.setState({
data: [],
});
console.log(data)
})
.catch((error) => {
console.log(error);
});
};
renderRow = ({item}) => {
return (
<View containerStyle={{ elevation: 1, borderRadius: 15 }}>
<View row>
<View flex={2}>
<Text h4>{item._id}</Text>
</View>
</View>
</View>
)
}
render() {
return (
<View style={styles.container}>
<Text h3 style={{ marginLeft: 10 }}>Choose your Listing!</Text>
<View>
<FlatList
style={{ marginHorizontal: 10, marginTop: 10 }}
data={this.state.data}
renderItem={this.renderRow}
keyExtractor={(item, index) => item._id}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
fontSize: 12,
textAlign: 'center',
margin: 5,
},
});
Error in console - This is the error that I am receiving in the console.
Error: Network Error at createError (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\axios\lib\core\createError.js:16)
at EventTarget.handleError (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\axios\lib\adapters\xhr.js:83)
at EventTarget.dispatchEvent (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\event-target-shim\dist\event-target-shim.js:818)
at EventTarget.setReadyState (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:575)
at EventTarget.__didCompleteResponse (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
at C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
at RCTDeviceEventEmitter.emit (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
at C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
at MessageQueue.__guard (C:\Users\dr460\reactnativeprojects\FirstApp\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373
)
The solve for this was fairly simplistic. I ended up doing some searching, but I was able to find a fix. Instead of using localhost, I was able to use 10.0.2.2 instead. This fixed the network error, however, I do have a data is not defined error now.

React native - is there a way to use an object from another page?

I want to know how can I use the "userPrincipalName" on other pages.
what do I need to do to make it work?
in my example, I try to use the "userPrincipalName" object on the MainScreenpage but I don't understand how to do it.
this my example of the Modal page which it has the object "userPrincipalName":
import React,
{ Component } from 'react';
import {
Text,
TouchableOpacity,
StyleSheet,
View,
} from 'react-native';
import Modal from 'react-native-modal';
import PlacesNavigator from '../navigation/PlacesNavigator';
import { LinearGradient } from 'expo-linear-gradient';
import { AzureInstance, AzureLoginView } from 'react-native-azure-ad-2';
const credentials = {
client_id: 'ea00ca9e-8c37-4520-8d80-2c2bb9239bf8',
scope: 'User.Read',
};
export default class Example extends Component {
constructor(props) {
super(props);
this.state = {
visibleModal: 3,
azureLoginObject: {},
loginSuccess: false
};
this.azureInstance = new AzureInstance(credentials);
this._onLoginSuccess = this._onLoginSuccess.bind(this);
}
_renderButton = () => (
<TouchableOpacity
onPress={() => this.setState({ visibleModal: false })}>
<LinearGradient
colors={['#4c669f', '#3b5998', '#192f6a']}
style={{
height: 80,
width: 180,
borderRadius: 10,
backgroundColor: "#2196F3",
justifyContent: 'center',
alignItems: 'center',
marginTop: 50,
}}>
<Text style={{ color: 'white', fontSize: 20, fontWeight: 'bold' }}>כניסה</Text>
</LinearGradient>
</TouchableOpacity>
);
_onLoginSuccess() {
this.azureInstance.getUserInfo().then(result => {
this.setState({
loginSuccess: true,
azureLoginObject: result,
});
console.log(result);
}).catch(err => {
console.log(err);
})
}
renderWelcomeMsg = (currentTime = new Date()) => {
const currentHour = currentTime.getHours()
const splitAfternoon = 12;
const splitEvening = 17;
if (currentHour >= splitAfternoon && currentHour <= splitEvening) {
return 'צהריים טובים,';
} else if (currentHour >= splitEvening) {
return 'ערב טוב,';
}
return 'בוקר טוב,';
}
render() {
if (!this.state.loginSuccess) {
return (
<AzureLoginView
azureInstance={this.azureInstance}
onSuccess={this._onLoginSuccess}
/>)
}
if (this.state.visibleModal === 3) {
const { givenName } = this.state.azureLoginObject;
const { userPrincipalName } = this.state.azureLoginObject;////THIS IS THE OBJECT I WANT
return (
<View style={styles.container}>
<Modal
isVisible={this.state.visibleModal === 3}
animationInTiming={1000}
animationOutTiming={1000}
backdropTransitionInTiming={4000}
backdropTransitionOutTiming={4000}
animationIn={'flipInY'}
>
<LinearGradient
colors={['#43D4FF', 'white']}
style={{ borderRadius: 10 }}>
<View style={styles.modalContent}>
<Text style={{
fontWeight: "bold",
fontSize: 35,
justifyContent: 'center',
alignItems: 'center',
}}>{this.renderWelcomeMsg()} {givenName}
</Text>
<View style={styles.buttonContainer}>
{this._renderButton()}
</View>
</View>
</LinearGradient>
</Modal>
</View>
);
}
return (
<PlacesNavigator />
);
}
}
And this is the MainScreen page that i want to use the object "userPrincipalName" in the Axios:
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
ActivityIndicator,
Platform,
FlatList,
TouchableOpacity,
TouchableHighlight,
WebView
} from "react-native";
import { HeaderButtons, Item } from "react-navigation-header-buttons";
import HeaderButton from "../components/HeaderButton";
import axios from "axios";
import moment from 'moment'
import storeService from '../components/storeService'
export default class MainScreen extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
userPrincipalName: null
};
}
getData = () => {
this.setState({ isLoading: true, data: [] })
axios.get("https://harigotphat1.mekorot.co.il/ConfirmPackaotWS/OrderApprove/OrderApp_Get_Orders_To_Approve/" + userPrincipalName.split('#')[0])
.then(res => {
this.setState({
isLoading: false,
data: res.data
});
console.log(res.data);
});
}
componentDidMount() {
this.props.navigation.setParams({ getData: this.getData });
// now we load the data we stored in the async storage
storeService.loadKey('userPrincipalName').then((res) => {
console.log("THIS IS THE userPrincipalName", res) //res will contain the value given the key, store this value in your state and use it any where in the component
})
this.getData()
// this.postData()
}
renderItems = (item, index) => {
const { merhavid, yaamID, ezorID, shemEzor } = item;
return (
<TouchableHighlight style={{
backgroundColor: '#ffff78'
}}>
<TouchableOpacity
style={{
paddingVertical: 15,
paddingHorizontal: 10,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
borderWidth: 0.8,
borderColor: '#d5d7db',
backgroundColor: index % 2 == 0 ? '#d1f0da' : '#f2f5f3',
}}
onPress={() => this.props.navigation.navigate("Info")}>
<Text style={styles.name}>
{ezorID + "" + " |" + " " + merhavid + " " + yaamID + " " + shemEzor}
</Text>
</TouchableOpacity>
</TouchableHighlight>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={{ flex: 0, paddingTop: 300 }}>
<Text style={{ alignSelf: "center", fontWeight: "bold", fontSize: 20 }}>טוען נתונים...</Text>
<ActivityIndicator size={'large'} color={'#08cbfc'} />
</View>
);
}
return (
<>
<View style={styles.container}>
<FlatList
data={this.state.data}
keyExtractor={(_, index) => String(index)}
renderItem={({ item, index }) => { return this.renderItems(item, index) }}
/>
</View>
<View style={styles.bottomMainContainer}>
<View style={styles.bottomView} >
<Text style={styles.bottomTextStyle}>סה"כ: {this.state.data.length} רשומות</Text>
</View>
</View>
</>
);
}
}
This is what React Context was designed for:
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
This also applies to updating data from nested components e.g.
const UserContext = React.createContext({
user: null,
setUser: () => {}
});
function UserContextProvider {
const [user, setUser] = useState(null);
return (
<UserContext.Provider value={{ user, setUser }}>
{props.children}
</UserContext.Provider>
)
}
function App() {
return (
<UserContextProvider>
<MainScreen />
</UserContextProvider>
);
}
class MainScreen extends Component {
static contextType = UserContext;
getData() {
// We should see the user details
console.log(this.context.user);
}
render() {
return (
<div>
<Example />
</div>
)
}
}
class Example extends Component {
static contextType = UserContext
_onLoginSuccess() {
this.azureInstance.getUserInfo().then(result => {
this.setState(...);
// set user in UserContext
this.context.setUser(result);
});
}
}
The best way would be use redux store which helps you create immutable data object which can be update only based on user action https://redux.js.org/basics/store/.
Another simple but not efficient way is to use the react native async storage, Where you store the object and later load it up in the componentDidMount() of your new component.
Another way is to pass these props as ScreenProps in your child component(this is only possible if the screens have a parent child relation)
solution - Sharing the object between components using asnc storage
import AsyncStorage from '#react-native-community/async-storage';
const storeService = {
async saveItem(key, value) {
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
console.log('AsyncStorage Error: ' + error.message);
}
},
loadKey(key) {
return new Promise((resolve, reject) => {
AsyncStorage.getItem(key)
.then(res => {
resolve(res)
})
.catch(err => reject(err));
});
}
};
export default storeService;
Note that these stateless component has 2 methods, One is to save against a key and another is to load.
Now to save a value against a key use
import React,
{ Component } from 'react';
....
export default class Example extends Component {
constructor(props) {
super(props);
....
}
....
render() {
...
if (this.state.visibleModal === 3) {
const { givenName } = this.state.azureLoginObject;
const { userPrincipalName } = this.state.azureLoginObject;
//this is how we will store the value when this component Example loads
storeService.saveItem('userPrincipalName', userPrincipalName)
return (
....
);
}
return (
<PlacesNavigator />
);
}
}
And to load this item again use
import React, { Component } from "react";
...
export default class MainScreen extends Component {
constructor(props) {
super(props);
this.state = {
userPricipalName: null //initialize this state variable
data: []
};
}
getData = () => {
...
var userPrincipalName = this.state.userPrincipalName;
axios.get("https://harigotphat1.mekorot.co.il/ConfirmPackaotWS/OrderApprove/OrderApp_Get_Orders_To_Approve/"+userPrincipalName.split('#')[0])
....
}
componentDidMount() {
// now we load the data we stored in the async storage
storeService.loadKey('userPrincipalName').then((res) => {
this.setState({userPricipalName: res}) //store like this
})
this.getData()
}
...
render() {
....
return (
....
);
}
}
Note that in order to be able to save a whole object in async store you will first need to stringify the object which storing and json parse while reading it again.

componentDidUpdate update logged just after click in screen

Im building a react native app and I faced a problem on componentDidUpdate.
When the app loads the componentDidMount call an api to check if the user are logged (using firebaseService.auth().onAuthStateChanged ), if it is, the app is redirected to main screen, otherwise to login screen. But the component just redirect to one of this screen when I click somewhere. Can someone help me?
Thanks
Follow my code:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button, Image, FlatList,ActivityIndicator} from 'react-native';
import logo from '../../asserts/logo.png'
import { TouchableOpacity, TextInput } from 'react-native-gesture-handler';
import ListCard from '../../components/User/ListCard';
import { connect } from 'react-redux';
import axios from 'axios';
import { restoreSession} from '../../store/actions/Section/actions';
class Load extends Component {
componentDidMount(){
this.props.restore();
const { user, logged, error, loading } = this.props;
console.log("restore");
if(user && logged) this.props.navigation.navigate('User');
}
componentDidUpdate(prevProps) {
const { user, logged, error,loading } = this.props;
console.log("aqui");
if (!loading && !prevProps.error && error) Alert.alert('error', error);
if (!loading && logged) this.props.navigation.navigate('User');
}
constructor() {
super();
this.state = {
animating: false,
align: 'flex-start',
alignsecond: false,
};
setTimeout(
() =>
this.setState({ align: 'flex-start' }, function() {
this.setState({
alignsecond: true,
});
}),
100
);
}
render() {
return (
<View
style={{
flex: 1,
alignItems: 'center',
//flexDirection: 'row',
justifyContent: this.state.align,
marginTop : 150,
}}>
<Image
source={logo}
style={{ width: 200, height: 200 }}
/>
{!this.state.alignsecond ? null : (
<View style={{ margin: 10, justifyContent:'center',alignItems:'center' }}>
<Text
style={{ color: '#6F1121', fontSize: 30, fontWeight: 'bold' ,justifyContent:'center'}}>
HomeShare
</Text>
<Text
style={{ fontSize: 15,justifyContent:'center' }}>
Find a place to Share !
</Text>
<ActivityIndicator style={{ marginTop:20 }} size="large" color="gray" />
</View>
)}
</View>
);
}
}
const styles = StyleSheet.create({
containerCard:{
flex:1,
flexDirection: 'column',
paddingTop:10 ,
paddingLeft:20,
paddingRight:20,
backgroundColor: 'rgba(220, 222, 211, 0.25)',
// marginTop: (Platform.OS === 'ios') ? 44 : StatusBar.currentHeight,
},
container:{
flex:1,
backgroundColor: 'rgba(220, 222, 211, 0.25)',
}
});
const mapStateToProps = ({ section: { restoring, loading, user, error, logged } }) => ({
restoring: restoring,
loading: loading,
user: user,
error: error,
logged: logged
});
const mapDispatchToProps = {
//login:loginUser,
restore:restoreSession
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Load);
My Action:
export const restoreSession = () => dispatch => {
dispatch(sessionLoading());
firebaseService.auth().onAuthStateChanged(async function(user) {
if (user) {
//console.log(user);
firebaseService.auth().currentUser.getIdToken(true).then(function(idToken) {
dispatch(sessionSuccess(idToken))
}).catch(function(error) {
dispatch(sessionError(e));
});
//dispatch(sessionSuccess(user));
} else {
dispatch(sessionLogout);
}
})
};
Personally, I would lose the logic for the componentDidMount and componentDidUpdate and just put the onAuthStateChange here in the componentDidMount so you can execute the navigate to the page.
Anyway, your problem is that the componentDidUpdate is executed when the page refreshes and that won't happen until you interact with it, and that is why it only analyzes the logged variable after you touch the screen. If you are thinking that the componentDidUpdate will execute every time you receive a new prop, that is wrong.
You should check this https://es.reactjs.org/docs/react-component.html#static-getderivedstatefromprops

Categories

Resources