I'm pulling data from the database, but I'm getting SyntaxError: Unexpected EOF React Native error when pulling data. Where's the problem?
class App extends Component {
fetch('http://..../tbl_menuler_tipsiparis.php')
.then((response) => response.json())
.then((responseJson) => {
firebase.database().ref('/TBL_SIPARISLER/tip').set(responseJson);
})
.catch((error) => {
console.error(error);
});
}
learn react State and Lifecycle
for your code
import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class componentName extends Component {
constructor(props) {
super(props);
this.fetchDataWithFetchAPI();
}
fetchDataWithFetchAPI = () => {
fetch('http://..../tbl_menuler_tipsiparis.php')
.then((response) => response.json())
.then((responseJson) => {
firebase.database().ref('/TBL_SIPARISLER/tip').set(responseJson);
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View>
<Text>{"SampleText"}</Text>
</View>
);
}
}
Related
I am trying to display data that I fetched with Axios. They came as an array. Because of this I cant show them. What should I do?
Here is my fetch code
componentDidMount() {
axios.post('http://192.168.1.106:80/partner_project_backend/project_list.php')
.then((response) => {
console.log(response.data)
})
.catch((error) => {
console.error(error);
});
}
Here is my console.log
I'm guessing you are getting the API response correctly and your only intention is to display the data in your application. If so, you could use the FlatList component from React Native
import React from 'react';
import { FlatList, Text } from 'react-native';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
};
}
componentDidMount() {
axios.get('http://192.168.1.106:80/partner_project_backend/project_list.php')
.then((response) => {
this.setState({ data: response.data });
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<FlatList
data={data}
renderItem={({ item }) => (
<Text>{item.name}</Text> // render your view here
)}
keyExtractor={item => item.id}
/>
);
}
}
React more about FlatList at https://reactnative.dev/docs/flatlist
To fetch data you have to use get method NOT post
this.state ={ data : null }
componentDidMount(){
axios.get('http://192.168.1.106:80/partner_project_backend/project_list.php')
.then((response) => {
this.setState({ data : response.data })
})
.catch((error) => {
console.error(error);
});
}
I want to refresh page data when I navigate back to it.
Here I'm going back:
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
this.renderResults(responseData)
setTimeout(() => {
this.props.navigation.navigate('HomeScreen');
}, 100)
})
.catch((error) => {
console.error(error);
});
when you go back you can add focus listener and refresh the data
import * as React from 'react';
import { View } from 'react-native';
function AppScreen({ navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// The screen is focused
// Call any action and update data
});
// Return the function to unsubscribe from the event so it gets removed on unmount
return unsubscribe;
}, [navigation]);
return <View />;
}
source : https://reactnavigation.org/docs/function-after-focusing-screen/
Instead of using focus listener, use the useFocusEffect hook which is designed for such use cases and provides a way to cleanup side-effects like useEffect does.
import * as React from 'react';
import { useFocusEffect } from '#react-navigation/native';
function App({ navigation }) {
useFocusEffect(
React.useCallback(() => {
let cleanedUp = false;
fetch('https://your/api')
.then((response) => response.json())
.then((responseData) => {
if (cleanedUp) {
// Ignore the results if the effect is no longer valid
// e.g. component was unfocused, not mounted anymore etc.
return
}
console.log(responseData);
renderResults(responseData);
setTimeout(() => {
navigation.navigate('HomeScreen');
}, 100);
})
.catch((error) => {
console.error(error);
});
return () => {
cleanedUp = true;
};
}, [navigation])
);
// Your component code
}
https://reactnavigation.org/docs/function-after-focusing-screen/#triggering-an-action-with-the-usefocuseffect-hook
I am using Redux in my React-Native application.
I am fetching the data from api call and on success rendoring it on ListItem.
I am able to fetch and display data but data is not auto updating unless and until I revisit the page.
Even values are not storing into the app
I am calling method from actions in constructor and componentDidMount method.
Can you Please check the code and tell me where am I going wrong.
Here is action.js
import {
FETCHING_PRODUCT_REQUEST,
FETCHING_PRODUCT_SUCCESS,
FETCHING_PRODUCT_FAILURE
} from './types';
export const fetchingProductRequest = () => ({
type : FETCHING_PRODUCT_REQUEST
});
export const fetchingProductSuccess = (json) => ({
type : FETCHING_PRODUCT_SUCCESS,
payload : json
});
export const fetchingProductFailure = (error) => ({
type : FETCHING_PRODUCT_FAILURE,
payload : error
});
export const fetchProduct = () => {
return async dispatch => {
dispatch(fetchingProductRequest());
try {
let response = await fetch("http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop");
let json = await response.json();
dispatch(fetchingProductSuccess(json));
} catch(error) {
dispatch(fetchingProductFailure(error));
}
}
}
My reducer.js
import {
FETCHING_PRODUCT_REQUEST,
FETCHING_PRODUCT_SUCCESS,
FETCHING_PRODUCT_FAILURE
} from './../actions/types';
const initialState = {
loading : false,
errorMessage : '',
shops: []
}
const products = ( state = initialState, action ) => {
switch(action.type) {
case FETCHING_PRODUCT_REQUEST :
return { ...state, loading: true} ;
case FETCHING_PRODUCT_SUCCESS :
return { ...this.state, loading: false, shops: action.payload };
case FETCHING_PRODUCT_FAILURE :
return { ...state, loading: false, errorMessage: action.payload};
}
};
export default products;
product.js
import * as React from 'react';
import { FlatList , ActivityIndicator} from 'react-native';
import { ListItem } from 'react-native-elements';
import { fetchProduct } from './../../actions/products';
import { connect } from 'react-redux';
import propTypes from 'prop-types';
class Product extends React.Component {
constructor(props) {
super(props);
this.props.fetchProduct();
this.state = {
loading : true,
shops : '',
isFetching: false,
active : true,
}
}
fetchProducts() {
const shopid = 13;
fetch(`http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop`)
.then(response => response.json())
.then((responseJson)=> {
this.setState({
loading: false,
shops: responseJson
})
alert(JSON.stringify(this.state.shops));
})
.catch(error=>console.log(error)) //to catch the errors if any
}
componentDidMount(){
// this.fetchProducts();
this.props.fetchProduct().then(this.setState({loading : false}));
}
renderItem = ({ item }) => (
<ListItem
title={item.name}
subtitle={item.name}
leftAvatar={{
source: item.avatar && { uri: item.avatar },
title: item.name[0]
}}
bottomDivider
chevron
/>
)
render () {
if(!this.state.loading)
{
if(this.props.shopsInfo.loading)
{
return (
<ActivityIndicator/>
)
}
else
{
return (
<FlatList
vertical
showsVerticalScrollIndicator={false}
data={this.props.shopsInfo.shops}
renderItem={this.renderItem}
/>
)
}
}
else
{
return (
<ActivityIndicator/>
)
}
}
}
Product.propTypes = {
fetchProduct: propTypes.func.isRequired
};
const mapStateToProps = (state) => {
return { shopsInfo: state };
}
function mapDispatchToProps (dispatch) {
return {
fetchProduct: () => dispatch(fetchProduct())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Product);
1. Not updating on data change from backend.
You have to call an api on regular interval to get updated data. Redux implementation doesn't mean it will fetch data from server whenever there is any change.
2. Even values are not storing into the app
If you are expecting redux will store data even if you will close/kill an application than it will not. You have persist data in-order to use it or store it in cache. Take a look at redux-persist
The problem is your passing wrong props in mapStateToProps function.
In reducer your updating the response value in shop props.
In order to get the updated value you need to pass shops property to get the value.
const mapStateToProps = (state) => {
const { shops: state };
return {shops};
}
I'm trying to implement login logic using redux, thunk, and navigation libraries in react native project (android) and I get unhandled promise rejection (id:0): (evalualting '_this.props.navigation')
any idea whats causing this problem or way out?
class AuthLoadingScreen extends React.Component {
constructor() {
super();
this._bootstrapAsync();
}
_bootstrapAsync = async () => {
this.props.getUserToken().then(() => {
this.props.navigation.navigate(this.props.token.token !== null ? Devices' : 'UserAuth');
}).catch(err => {
this.setState({ err })
})
};
render() {
return (
<View>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
// actionCreator.js
export const getUserToken = () => dispatch =>
AsyncStorage.getItem('userToken')
.then((data) => {
dispatch(loading(false));
dispatch(getToken(data));
})
.catch((err) => {
dispatch(loading(false));
dispatch(error(err.message || 'ERROR'));
})
You are calling
this._bootstrapAsync() inside constructor place it in the componentDidMount
class AuthLoadingScreen extends React.Component {
constructor() {
super();
}
componentDidMount() {
this._bootstrapAsync();
}
....
}
The action prop doesn't return a promise.
Also, I would suggest you call navigation inside the action with help for react-navigation-redux-helpers.
Use navigation in actions.
export const getUserToken = () => dispatch => {
AsyncStorage.getItem('userToken')
.then((data) => {
dispatch(loading(false));
dispatch(getToken(data));
dispatch(NavigationActions.navigate('successRoute'))
})
.catch((err) => {
dispatch(loading(false));
dispatch(error(err.message || 'ERROR'));
dispatch(NavigationActions.navigate('failRoute'))
});
}
Not a good practise returning a promise to dispatch.
I am trying to display admob Interstitial, but I have this error. The admob banner works fine, and the only issue is with Interstitial.
This is my code:
import {AdMobInterstitial} from 'react-native-admob';
componentDidMount() {
AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/1033173712');
AdMobInterstitial.requestAd().then(() => AdMobInterstitial.showAd());
}
Screenshot
import {AdMobBanner,AdMobInterstitial,PublisherBanner,AdMobRewarded} from 'react-native-admob';
class Alpha extends React.Component {
componentWillMount(){
this.makeAdmobRequest();
setTimeout(()=>{
this.makeRemoteRequest()
},1000);
setTimeout(()=>{
this.showInterstitial()
},60000);
}
makeAdmobRequest=()=>{
return fetch('http://url/admob_setting.php?cat_id=2')
.then((response) => response.json())
.then((responseJson) =>
{
var bannerid1=responseJson[0]['banner_add'];
this.setState({
bannerid1:responseJson[0]['banner_add'],
interestitialid:responseJson[0]['interestial_add'],
});
})
.catch((error) =>
{
console.error(error);
});
}
renderAdd(){
if(this.state.bannerid1){
return(
<View style={{flex:1}}>
<AdMobBanner
adSize="banner"
adUnitID={this.state.bannerid1}
testDeviceID="EMULATOR"
didFailToReceiveAdWithError={this.bannerError} />
</View>
);
}
}
showInterstitial() {
AdMobInterstitial.setTestDevices([AdMobInterstitial.simulatorId]);
AdMobInterstitial.setAdUnitID(this.state.interestitialid);
AdMobInterstitial.requestAd().then(() => AdMobInterstitial.showAd());
}
render() {
.......
}
}