I am new using native react, I am developing a project that consists in showing the data of an Api in my project. I have seen tutorials and most, if not all, use the same Api:
But what I want is to be able to show the data of a local API that connects to a local BD as well, which is why I developed a Web API with ASP.Net, I was guided by this
Create a DB in SQL Server (which is the DB that I want to use for this project) and generate the API; the API works correctly, tested with POSTMAN.
Now the problem is that I want to use it in my project, and following the tutorial that is on the official page of React Native in the section does not work for me.
This is my code:
import React from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
export default class FetchExample extends React.Component {
constructor(props){
super(props);
this.state ={ isLoading: true}
}
componentDidMount(){
return fetch('http://192.168.2.19:53943/api/users')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.users,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render(){
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View style={{flex: 1, paddingTop:20}}>
<FlatList
data={this.state.dataSource}
renderItem={({item}) => <Text>{item.Name}, {item.Email}</Text>}
keyExtractor={({id}, index) => id}
/>
</View>
);
}
}
The error message that I get when I execute my project is THIS
JSON Parse Error: Unrecognized Token
What could I be doing wrong? I suspect that it may be the URL that happened to the FETCH, since it eliminates all of the render () and only leaves a showing a message and the same error keeps coming up. Thank you
hi you shuld add this code in Global.asax Application_Start() :
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
and add this code in WebApiConigg :
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
rest visual stdio and run again project WebApi address
stop react-native emulator => cntrl+ c react-native-run-android
Related
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { View, Text } from 'react-native';
const PostsList = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.defaults.headers.common['Authorization'] = 'mykey';
axios.get('http://myurl')
.then(res => {
setPosts(res.data);
})
.catch(error => console.error(error));
}, []);
return (
<View>
{posts.map(post => (
<Text key={post.id}>{post.title.rendered}</Text>
))}
</View>
);
};
export default PostsList;
I'm asking help because I have a problem with React Native and the WordPress REST API. I am trying to access it with Axios but it returns the following error: ERROR [AxiosError: Network Error]
I am using Expo and testing it on my own Android device (not an emulator). It should be noted that my WordPress is hosted locally and I have tried specifying my IP, but to no avail. Does anyone can help me please ?
Thank you.
I tried to put my own ip and to disable my firewall
I am having trouble implementing "Sign in with Facebook" Authentication in my mobile application. I have a feeling I am missing something tiny but can't seem to crack it.
StartScreen.js
import {signInWithFacebook, FacebookAuthProvider, signInWithPopup} from 'firebase/auth'
import { auth, facebookProvider } from '../firebase'
const signInWithFacebook = () => {
signInWithFacebook(auth, facebookProvider)
.then((re) =>{
console.log(re);
})
.catch((err)=>{
(err.message)
})
}
I have tried signUpWithPopUp and signInWithFacebook, but I am beginning to think there is an issue inside the function itself. With the current screenshot, I am receiving a "Maximum call stack size exceeded." error.
Firebase.js
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const facebookProvider = new FacebookAuthProvider();
export { auth, facebookProvider }
I have tried removing facebookProvider from the function, using just "auth", and that is not working either, receiving the same error.
I have attempted different combinations between the parameters I am passing and whether I am using signInWithFaceBook or signInWithPopup.
In case it is relevant, here is the button I am using:
startscreen.js
<TouchableOpacity
onPress = {signInWithFacebook}>
<View
style={[
styles.login_social_button,
styles.login_social_facebook,
]}>
<List.Icon style = {styles.login_social_icon} icon="facebook" />
</View>
</TouchableOpacity>
Thank you
My group and I are currently working on a mobile app using expo-cli and firebase as the backend. One of the requirements is we need to get users' screen time and record how frequently users press certain buttons. According to expo firebase documentation, it only supports limited Firebase Analysis. We were wondering what would be the best way to use Firebase Analytics with Expo to capture screen time and button pressed frequencies.
Screen Tracking
Screen tracking in React Native is different than in a native app since some navigation libraries run inside one Activity/Viewcontroller.
Assuming you are using react-native-navigation, which does have full native navigation support you can handle screen tracking like this.
import analytics from '#react-native-firebase/analytics';
import { Navigation } from 'react-native-navigation';
Navigation.events().registerComponentDidAppearListener(async ({ componentName, componentType }) => {
if (componentType === 'Component') {
await analytics().logScreenView({
screen_name: componentName,
screen_class: componentName,
});
}
});
Look here for the documentation
If you are using react-navigation you can still work around the lack of native screen support by hooking into the events that are provided.
import analytics from '#react-native-firebase/analytics';
import { NavigationContainer } from '#react-navigation/native';
const App = () => {
const routeNameRef = React.useRef();
const navigationRef = React.useRef();
return (
<NavigationContainer
ref={navigationRef}
onReady={() => {
routeNameRef.current = navigationRef.current.getCurrentRoute().name;
}}
onStateChange={async () => {
const previousRouteName = routeNameRef.current;
const currentRouteName = navigationRef.current.getCurrentRoute().name;
if (previousRouteName !== currentRouteName) {
await analytics().logScreenView({
screen_name: currentRouteName,
screen_class: currentRouteName,
});
}
routeNameRef.current = currentRouteName;
}}
>
...
</NavigationContainer>
);
};
export default App;
Here you can find a full example starter app.
Button Press Events
For logging press events there's a lot of documentation on the RNFirebase website.
A simple example to track a custom event that could be an onPress or anything would look like this:
import react, { useEffect } from 'react';
import { View, Button } from 'react-native';
import analytics from '#react-native-firebase/analytics';
function App() {
return (
<View>
<Button
title="Add To Basket"
onPress={async () =>
await analytics().logEvent('onPressAddToBasket', {
id: 3745092,
item: 'Your product name',
description: ['round neck', 'long sleeved'],
size: 'L',
wheneverYouWantToTrack: true,
})
}
/>
</View>
);
}
I'm new to React Native. I am sending a link to the app with "push notification". When I tested it, everything works both in the background and when the application is closed. But every time I open the application, I get the following warning. How can I resolve this situation?
WARN Possible Unhandled Promise Rejection (id: 0):
TypeError: null is not an object (evaluating 'remoteMessage.data')
My codes:
import React, { useEffect } from 'react'
import { Button, Linking, View } from 'react-native'
import styles from './styles/SplashStyles'
import messaging from '#react-native-firebase/messaging'
import { DASHBOARD } from '../navigation/routesNames'
const Splash = ({ navigation }) => {
useEffect(async () => {
messaging()
.subscribeToTopic('users')
.then(() => console.log('Subscribed to topic!'));
//Notification caused app to open from background state:'
messaging()
.onNotificationOpenedApp(remoteMessage => {
if (remoteMessage.data.url) {
Linking.openURL(remoteMessage.data.url)
}
});
//Notification caused app to open from quit state
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage.data.url) {
Linking.openURL(remoteMessage.data.url)
}
});
}, [])
return (
<View style={styles.container}>
<Button
title={"Start"}
onPress={() => {
navigation.reset({
index: 0,
routes: [{ name: DASHBOARD }]
})
}}
/>
</View>
)
}
export default Splash
I think it is because at initialization, the value for remoteMessage is not yet defined when it is rendered specifically via remoteMessage.data, causing the error. If you don't mind introducing a dependency on the lodash package, there's a helper called 'has' that checks if path exists. For example:
if (_.has(remoteMessage, 'data.url') { ....
I am in need of help with my web app that is uploading an image to firebase storage then wanting to display that image in a thumbnail.
I am getting the error this.xhr_ = new XMLHTTPREQUEST is not defined
I don't have 10 rep points so it seems I can't upload my image directly.
If there was a better way to do this please let me know.
I have looked through firebase docs and many stack overflow answers but can seem to have anything that works. I have tried to globally install xmlhttprequest, also as a dependency.
As you can see I also attempted to import XmlHttpRequest but it did nothing.
The error I am getting comes from the last statement with getdownloadurl()
<script>
import XMLHTTPREQUEST from 'xmlhttprequest'
import ImageCard from '../../components/ImageCard/ImageCard'
import {db} from '../../firebase/init.js'
import {storage} from '../../firebase/init.js'
export default {
name: "explore",
components: {
ImageCard,
db,
storage,
XMLHTTPREQUEST
},
data() {
return {
cards: [],
downloadUrl: ''
}
},
created(){
//fetch data from firestore
db.collection('Assets').get()
.then(snapshot => {
snapshot.forEach( doc => {
let card = doc.data()
console.log(card)
// the card.id is adding an id property onto the let card variable
card.id = doc.id
this.cards.push(card)
console.log(this.cards)
})
})
},
created() {
const storageRef = storage.ref()
const imagesRef = storageRef.child('AshAngelPaid.jpg');
console.log('Before getting requesting download url')
imagesRef.getDownloadURL().then( (url) => {
document.querySelector('img').src = url;
console.log('got download url');
Basically, while nuxtjs is rendering your component on the server side there's no xmlhttprequest, just move .getDownloadURL and related stuff into mounted() or beforeMount() lifecycle hook.