React Native retrieving API data source.uri should not be an empty string - react-native

I am trying to retrieve data from an API (https://developers.zomato.com/documentation) and get title of restaurants and an image with it. However when I try to load an image I get a warning source.uri should not be an empty string.
Here is my code as it stands:
async componentDidMount() {
let id = this.props.navigation.state.params.category
let result;
try {
result = await axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/search?category=${id}`,
headers: {
'Content-Type': 'application/json',
'user-key': "a31bd76da32396a27b6906bf0ca707a2",
},
})
} catch (err) {
err => console.log(err)
}
this.setState({
isLoading: false,
data: result.data.restaurants
})
}
render() {
return (
<View>
{
this.state.isLoading ?
<View style={{ flex: 1, padding: 20 }}>
<ActivityIndicator style={{color:'red'}} />
</View> :
(
this.state.data.length == 0 ?
<View style={{ flex: 1, padding: 20 }}>
<Text style={{ color: '#000', fontWeight: 'bold' }}>No restaurants from selected category</Text>
</View> :
<FlatList
style={{ marginBottom: 80 }}
keyExtractor={item => item.id}
data={this.state.data}
renderItem={({ item }) =>
<TouchableHighlight onPress={()=> console.log(item.restaurant.thumb)}>
<Card image={item.restaurant.thumb} style={styles.container}>
<Image resizeMode='contain' source={{ uri: item.restaurant.thumb }}/>
<Text style={{color:'#000',fontWeight:'bold'}}>{item.restaurant.name} </Text>
</Card>
</TouchableHighlight>
}
/>
)
}
</View>
);
}
as you can see when I touch the any of the cards I am console logging the link of the image uri and it shows up perfectly. Why is that when the app loads the images they are empty strings yet when I load it though console log the link shows up perfectly?
I am using axios to load my API
here is an expo snack link: https://snack.expo.io/r1XTaw4JU

So i got 2 issues, one is in the card component you were not providing the uri properly it should be image={{uri:item.restaurant.thumb}} and secondly for newyork your entity id must be
To search for 'Italian' restaurants in 'Manhattan, New York City',
set cuisines = 55, entity_id = 94741 and entity_type = zone
Its as per zomato docs,so do check out that. and find expo link : expo-snack
import React from 'react';
import {
View,
Text,
FlatList,
StyleSheet,
Button,
TouchableHighlight,
ActivityIndicator,
} from 'react-native';
import { createAppContainer } from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import { Card, Image } from 'react-native-elements';
import Constants from 'expo-constants';
import axios from 'axios';
export default class CategoryScreen extends React.Component {
constructor(props){
super(props);
this.state={
data : [],
isVisible: true,
city : '94741'
}
}
async componentDidMount() {
let id = "3"
let city = this.state.city
let result;
try {
result = await axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/search?entity_id=${city}&entity_type=zone&category=${id}`,
headers: {
'Content-Type': 'application/json',
'user-key': "a31bd76da32396a27b6906bf0ca707a2",
},
})
} catch (err) {
err => console.log(err)
}
this.setState({
isLoading: false,
data: result.data.restaurants
})
console.log(result)
console.log(data)
}
render() {
return (
<View>
{
this.state.isLoading ?
<View style={{ flex: 1, padding: 20 }}>
<ActivityIndicator style={{color:'red'}} />
</View> :
(
this.state.data.length == 0 ?
<View style={{ flex: 1, padding: 20 }}>
<Text style={{ color: '#000', fontWeight: 'bold' }}>No restaurants from selected category</Text>
</View> :
<FlatList
style={{ marginBottom: 80 }}
keyExtractor={item => item.id}
data={this.state.data}
renderItem={({ item }) =>
<TouchableHighlight onPress={()=> alert(item.restaurant.location.city)}>
<Card image={{uri:item.restaurant.thumb}} style={styles.container}>
<Text style={{color:'#000',fontWeight:'bold'}}>{item.restaurant.name} </Text>
</Card>
</TouchableHighlight>
}
/>
)
}
</View>
);
}
};
const styles = StyleSheet.create({
});

Related

React Native - TextInput does not get updated and is stuck with its initial state which is empty onSubmitEditing

The setSearchTerm does not get updated and is stuck with empty string all the time when i hit "done" on the keyboard. Any suggestions?
// React Native Bottom Navigation
// https://aboutreact.com/react-native-bottom-navigation/
import React, { useState } from 'react';
import { View, Text, SafeAreaView, Dimensions, FlatList, TouchableOpacity, TextInput } from 'react-native';
import { WebView } from 'react-native-webview';
import
MaterialCommunityIcons
from 'react-native-vector-icons/MaterialCommunityIcons';
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
const SearchScreen = ({navigation}) => {
const [searchTerm, setSearchTerm] = useState('');
const [data, dataSet] = useState({})
const onSearchText = async() => {
alert(searchTerm);
dataSet({});
let txtSearch = searchTerm;
if(txtSearch.length > 0){
//alert(searchTerm);
let response = await fetch('https://xxxxxx',{
headers: {
'Accept': 'application/json, text/plain',
'Content-Type': 'application/json;charset=UTF-8'
},
method: 'POST',
body: JSON.stringify({ searchTerm: searchTerm }),
mode: 'no-cors',
})
response = await response.json();
alert(JSON.stringify(response.results));
//alert(JSON.stringify(response.results));
dataSet(response.results);
}else{
}
}
React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () =>
<View style={{flexDirection:'row'}}>
<TextInput
placeholder='Search Here'
onChangeText={term => setSearchTerm(term)}
onSubmitEditing={onSearchText} style={{backgroundColor:'#B2DFDB',marginRight:20,width:windowWidth - 125, padding:5, borderRadius:5,}}/>
</View>
,
});
}, [navigation, ]);
const renderItem = ({ item }) => (
<TouchableOpacity
onPress={() => navigation.navigate("Display", { url: item.url, youtube: item.youtube })}>
<View style={{flexDirection:'row', marginBottom:20,padding:10,backgroundColor:'#B2DFDB',borderRadius:10,}}>
<View pointerEvents="none" style={{}}>
<WebView style={{width:200, height:130, }} source={{ uri: item.url }} />
</View>
<View style={{ marginLeft:10, }}>
<Text style={{color:'#00796B', flexWrap: 'wrap',}}>{item.source}</Text>
<View style={{flexDirection:'row', flex:1,}}>
<Text style={{color:'#000000', fontWeight:'bold', flex:1, flexWrap: 'wrap'}}>{item.title}</Text>
</View>
<Text style={{color:'#00838F', }}>{item.category}</Text>
<Text style={{color:'#00838F', }}>{item.country}</Text>
</View>
</View>
</TouchableOpacity>
);
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1 , padding: 16, backgroundColor:'#E0F2F1',}}>
{
data.length > 0 ? (
<FlatList
style={{flex:1,}}
data={data}
renderItem={renderItem}
keyExtractor={item => item.id}
/>) : <View style={{flex:1,justifyContent:'center',alignItems:'center', }}><Text style={{color:'#80CBC4', fontSize:20, textAlign:'center'}}>Nothing found, please try and search again.</Text></View>
}
</View>
</SafeAreaView>
);
}
export default SearchScreen;
You don't currently have a value assigned to the textInput field. Adding a value of searchTerm should resolve it.
React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () =>
<View style={{flexDirection:'row'}}>
<TextInput
placeholder='Search Here'
onChangeText={term => setSearchTerm(term)}
value={searchTerm}
onSubmitEditing={onSearchText} style={{backgroundColor:'#B2DFDB',marginRight:20,width:windowWidth - 125, padding:5, borderRadius:5,}}/>
</View>
,
});
}, [navigation, ]);

React native WARN Possible Unhandled Promise Rejection (id: 2): Error: [AsyncStorage] Passing null/undefined as value is not supported

In react native cli i was trying to login but not working nd same thing working fine in expo nd this error is showing please let me know what can i do to do this???? i have added the action ,reducer,component page
getting error this //
WARN Possible Unhandled Promise Rejection (id: 2):
Error: [AsyncStorage] Passing null/undefined as value is not supported. If you want to remove value, Use .removeItem method instead.
Passed value: undefined
Passed key: userToken
checkValidInput#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.easylab&modulesOnly=false&runModule=true:146791:24
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.easylab&modulesOnly=false&runModule=true:146835:24..........................
my action is like this // actions>index.js page
export const login = (formValues, actions) => {
return async dispatch => {
dispatch(startSubmitting());
const url = `/auth/login`;
var formdata = new FormData();
formdata.append('email', formValues.email);
formdata.append('password', formValues.password);
const response = await api
.post(url, formdata)
.then(res => {
return res;
})
.catch(error => {
actions.setErrors(error.response.data.error);
return error.response;
});
dispatch({
type: 'LOGIN',
payload: response,
});
dispatch(stopSubmitting());
await AsyncStorage.setItem('userToken', response.data.access_token);
};
};
//my component page login.js
import { StatusBar } from "expo-status-bar";
import React, { useState, useEffect } from "react";
import {
Field,
Form,
Formik,
FormikProps,
ErrorMessage,
useFormik,
} from "formik";
import { connect } from "react-redux";
import { login } from "../../../actions";
import { Button } from "react-native-paper";
import ErrorMsg from "./ErrorMsg";
class Login extends React.Component {
submitLogin = (values, actions) => {
this.props.login(values, actions);
};
render() {
const { onChangeText, text, navigation } = this.props;
const { isSubmitting ,isLoading} = this.props.commonData;
const { login, loginLoading, isLoggedIn } = this.props.loginForm;
{
login && this.props.navigation.navigate("Nav1");
}
return (
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container}
>
{/* {verifyOtp ? <Loader loading={verifyOtp} /> : null} */}
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.inner}>
<View style={{ alignItems: "center" }}>
<Image
source={require("../../../assets/images/diabetes-awareness-month-1440x810.jpg")}
style={{
height: 110,
// top: -20,
resizeMode: "contain",
}}
/>
</View>
<View style={{}}>
<Text onPress={() => this.props.navigation.navigate("Register")}>
New User ? Register
</Text>
</View>
<View style={{}}>
<Text style={{ fontSize: 24, fontWeight: "bold" }}>LOGIN</Text>
</View>
<View style={{}}>
<Formik
initialValues={{
email: "",
password: "",
}}
validate={(values) => {
const error = {};
if (!values.password) {
error.password = (
<Text style={{ color: "red", fontSize: 10 }}>
Password Required
</Text>
);
}
if (!values.email) {
error.email = (
<Text style={{ color: "red", fontSize: 10 }}>
Email Type Required
</Text>
);
}
return error;
}}
onSubmit={(values, actions) => {
this.submitLogin(values, actions);
}}
enableReinitialize={true}
>
{(props: FormikProps<any>) => (
<>
<View style={{ paddingBottom: 10 }}>
<Text>Login To Check Your Account</Text>
</View>
<View>
{/* email */}
<View style={{ marginBottom: 20 }}>
<View style={styles.textInputContainer}>
<MaterialCommunityIcons
style={{ alignSelf: "center", paddingLeft: 10 }}
name="email"
size={28}
/>
<TextInput
style={styles.input}
onChangeText={props.handleChange("email")}
value={props.values.email}
autoFocus={true}
placeholder="Email"
/>
</View>
</View>
<View style={{ marginBottom: 20 }}>
<View style={styles.textInputContainer}>
<MaterialCommunityIcons
style={{ alignSelf: "center", paddingLeft: 10 }}
name="security"
size={28}
/>
<TextInput
style={styles.input}
onChangeText={props.handleChange("password")}
maxLength={10}
secureTextEntry={true}
value={props.values.password}
placeholder="Password"
/>
</View>
</View>
{/* {props.touched.password && props.errors.password && ( */}
<ErrorMsg msg={props.errors.password} />
{/* )} */}
<TouchableHighlight
underlayColor="white"
onPress={props.handleSubmit}
>
<Text color="white" style={styles.buttonStyle}>
{/* {isSubmitting ? (
<ActivityIndicator
size="small"
color="#4DB2F8"
/>
) : ( */}
<Text>LOGIN </Text>
{/* )} */}
</Text>
</TouchableHighlight>
</View>
</>
)}
</Formik>
</View>
</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
);
}
}
const mapStateToProps = (state) => {
return {
loginForm: state.loginData,
commonData: state.commonFunctions,
};
};
export default connect(mapStateToProps, { login })(Login);
and in redux trying to store like this// reducers>index.js page
const loginReducer = (
state = {
otp: false,
mobile: null,
login: false,
loginLoading: true,
verifyOtp: false,
isLoggedIn: false,
},
action
) => {
switch (action.type) {
case "LOGIN": {
if (action.payload.status === 200) {
let newState = { ...state, login: true, isLoggedIn: true };
return newState;
} else {
let newState = { ...state, login: false, isLoggedIn: false };
return newState;
}
}
default:
return state;
}
};
export default combineReducers({
loginData: loginReducer,
});
Your problem is that you are trying to set userToken to null on this line:
await AsyncStorage.setItem('userToken', response.data.access_token);
You need to do a null check before setting the token, since Async Storage does not support setting null values. Try:
if (response && response.data && response.data.access_token) {
await AsyncStorage.setItem('userToken', response.data.access_token);
}

How can use useState() with Flatlist data?

I've had a problem when i used useState(). i have to filter by searched words on my data and list.
i need to define my data list with State (i'd list with searched words) but when i use State, i've taken 'Invalid Hook' error.
let [list, setList] = useState(data);
//called
data={list}
I don't find where i use that , I couldn't fix for 3 days, i can't reach next step :( I hope i'll fix with expert helps...
import React, {Component, useState} from 'react'
import {
Text,
StyleSheet,
View,
FlatList,
SafeAreaView,
ScrollView,
Image,
TextInput,
} from 'react-native'
import data from '../../data'
export default class Flatlistexample extends Component {
render () {
//defined below
let [list, setList] = useState(data);
seachFilter=(text)=>{
const newData = data.filter(item=>{
const listitem= `${item.name.toLowerCase()} ${item.company.toLowerCase()}`;
return listitem.indexOf(text.toLowerCase())
})
};
return (
<SafeAreaView
style={{
flex: 1,
}}>
<FlatList
//called
data={list}
renderItem={({item, index})=>{
return (
<ScrollView>
<SafeAreaView
style={[
styles.container,
{backgroundColor: index % 2 === 0 ? '#fafafa' : '#bbb'},
]}>
<Image style={styles.profile} source={{uri: item.picture}} />
<View style={styles.rightside}>
<Text style={styles.name}>{item.name}</Text>
<Text style={styles.company}>{item.company}</Text>
</View>
</SafeAreaView>
</ScrollView>
)
}}
keyExtractor={item => item._id}
ListHeaderComponent={() => {
const [search, setSearch] = useState('');
return (
<View style={styles.seachContainer}>
<TextInput
style={styles.textInput}
placeholder={'Search...'}
value={search}
onChangeText={text=>{
setSearch(text)
}}
></TextInput>
</View>
)
}}
/>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
borderBottomWidth: 1,
borderColor: 'gray',
},
profile: {
width: 50,
height: 50,
borderRadius: 25,
marginLeft: 10,
},
rightside: {
marginLeft: 20,
justifyContent: 'space-between',
marginVertical: 5,
},
name: {
fontSize: 22,
marginBottom: 10,
},
searchContainer: {
padding: 10,
borderWidth: 2,
borderColor: 'gray',
},
textInput: {
fontSize: 16,
backgroundColor: '#f9f9f9',
padding: 10,
},
})
Thank you
React hooks can be used with functional component only, here you are using class component
You need to understand the difference between functional component and class component first.
Here you are using class component so your state should be manageed in the following way
export default class Flatlistexample extends Component {
constructor(props)
{
this.state={list:[]}
}
}
and to update list
this.setState({list: <array of data>})
If you want to use hooks, your component needs to be changed something like the following:
const Flatlistexample = () => {
//defined below
let [list, setList] = useState(data);
seachFilter = (text) => {
const newData = data.filter(item => {
const listitem = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`;
return listitem.indexOf(text.toLowerCase())
})
};
return (
<SafeAreaView
style={{
flex: 1,
}}>
<FlatList data={list} renderItem={Your flatlist Item}/>
</SafeAreaView>
)
}
export default Flatlistexample
Here you go, I've added lots of comments. I hope you find this instructive. Let me know if you have questions!
import React, { useMemo, useState } from 'react'
import {
Text,
StyleSheet,
View,
FlatList,
SafeAreaView,
ScrollView,
Image,
TextInput,
} from 'react-native'
import data from '../../data'
// changed this to a functional component so you can use hooks. You can't use hooks in class components.
const Flatlistexample = () => {
// you don't actually need to `useState` for your list, since you're always just filtering `data`
// you would need to use `useState` if you were receiving data from an API request, but here it's static
const [search, setSearch] = useState('') // this should live in the main component so you can filter the list
const parsedSearch = search.toLowerCase() // do this once outside the filter, otherwise you're converting it for each item in the data array
const filteredList = useMemo(
() =>
data.filter(item => {
const itemText = `${item.name.toLowerCase()} ${item.company.toLowerCase()}`
return itemText.indexOf(parsedSearch) > -1 // returns `true` if search is found in string
}),
[parsedSearch], // this will only run if parsedSearch changes
)
return (
<SafeAreaView style={{ flex: 1 }}>
<FlatList
//called
data={filteredList} // use the filtered list here
renderItem={({ item, index }) => {
return (
<ScrollView>
<SafeAreaView
style={[
styles.container,
{ backgroundColor: index % 2 === 0 ? '#fafafa' : '#bbb' },
]}
>
<Image style={styles.profile} source={{ uri: item.picture }} />
<View style={styles.rightside}>
<Text style={styles.name}>{item.name}</Text>
<Text style={styles.company}>{item.company}</Text>
</View>
</SafeAreaView>
</ScrollView>
)
}}
keyExtractor={item => item._id}
ListHeaderComponent={() => {
return (
<View style={styles.seachContainer}>
<TextInput
style={styles.textInput}
placeholder={'Search...'}
value={search}
onChangeText={text => {
setSearch(text)
}}
/>
</View>
)
}}
/>
</SafeAreaView>
)
}
export default Flatlistexample

Results do not update after a change of state

I have a problem, when I do a search, I get the data from my API, the first time I do a search, everything is fine, all the data is displayed. However, when I do a second search immediately, nothing is updated.
I put in console.log, and I see that I'm getting this data back, yet the display is not updated.
import React, { Component } from "react";
import { SafeAreaView, StyleSheet } from "react-native";
import Search from "./Component/Search";
export default class App extends Component {
render() {
return (
<SafeAreaView style={styles.container}>
<Search />
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
import React from "react";
import { View, TextInput, Button, FlatList, StyleSheet } from "react-native";
import LivreItem from "../Component/LivreItem";
class Search extends React.Component {
constructor(props) {
super(props);
this.inputValue = "";
this.state = { livres: [] };
}
searchBooks = async () => {
const key = "&key=XXXXXXXXXXXXXXXXXXXXXXX";
const url = "https://www.googleapis.com/books/v1/volumes?q=" + this.inputValue + key;
return fetch(url)
.then(response => response.json())
.catch(e => {
console.log("Une erreur s'est produite");
console.log(e);
});
};
getBooks = () => {
if (this.inputValue.length > 0) {
this.searchBooks()
.then(data => this.setState({ livres: data.items }))
.catch(reject => console.log(reject));
}
};
changeText = text => {
this.inputValue = text;
};
render() {
return (
<View style={styles.header_container}>
<View style={styles.sub_container}>
<TextInput
onChangeText={text => this.changeText(text)}
style={styles.input}
placeholder="Ex: Harry Potter"
/>
<Button
style={styles.button}
title="Rechercher"
onPress={() => this.getBooks()}
/>
</View>
<FlatList
style={styles.list}
data={this.state.livres}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <LivreItem livre={item.volumeInfo} />}
/>
</View>
);
}
}
const styles = StyleSheet.create({
sub_container: {
justifyContent: "space-between",
flexDirection: "row",
marginTop: 30,
paddingRight: 10,
paddingLeft: 10
},
header_container: {
flex: 1,
flexDirection: "column",
padding: 10
},
input: {
borderRadius: 4,
borderWidth: 0.5,
borderColor: "#d6d7da",
width: 150,
paddingLeft: 5
},
button: {
borderRadius: 4
},
list: {
paddingLeft: 15,
paddingRight: 15
}
});
export default Search;
import React from "react";
import { View, StyleSheet, Image, Text } from "react-native";
class LivreItem extends React.Component {
constructor(props) {
super(props);
this.state = { livre: this.props.livre};
this.description =
this.state.livre.description === null || this.state.livre.description === undefined
? "Pas de description disponible"
: this.state.livre.description;
this.img = this.state.livre.imageLinks;
this.image =
this.img === undefined ||
this.img.smallThumbnail === undefined ||
this.img.smallThumbnail === null
? null
: this.state.livre.imageLinks.smallThumbnail;
}
render() {
return (
<View style={styles.content}>
<View>
<Image style={styles.image} source={{ uri: this.image }} />
<Image style={styles.image} source={this.image} />
</View>
<View style={styles.content_container}>
<Text style={styles.titre}>{this.state.livre.title}</Text>
<Text style={styles.description} numberOfLines={4}>
{this.description}
</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
content: {
height: 125,
flexDirection: "row",
marginTop: 15
},
content_container: {
flexDirection: "column",
flexShrink: 1,
marginLeft: 10
},
image: {
width: 100,
height: 100
},
titre: {
fontWeight: "bold",
flexWrap: "wrap"
},
description: {
flexWrap: "wrap"
}
});
export default LivreItem;
Thanks.
Configure the prop extraData in Flatlist component ala:
<FlatList
extraData={this.state.livres}
/>
Pass a boolean value to the FlatList extraData.
<FlatList
extraData={this.state.refresh}
/>

React Native Zomato API reviews not being displayed

I am trying to display review information from the Zomato API however for some reason nothing is being displayed.
I am using a FlatList to put it all out there, but every time I compile the code nothing seems to show up.
Here is all my code regarding the subject:
<Text>REVIEWS:</Text>
{this.state.data.all_reviews_count == 0 ?
<View style={{ flex: 1, padding: 20, marginTop:0}}>
<Text style={{ color: '#000', fontWeight: 'bold' }}>No reviews for this restaurant yet</Text>
</View> :
<FlatList
keyExtractor={item => item.id}
showsVerticalScrollIndicator={false}
data={this.state.data}
renderItem={({ item }) =>
<View>
<Text>{item.all_reviews_count}</Text>
</View>}/>}
I have other data being retrieved and it's all being outputted just fine. for some reason the review section seems to be weird.
I also checked to see how reviews are displayed in the terminal and this is what I got:
"all_reviews": Object {
"reviews": Array [
Object {
"review": Array [],
},
Object {
"review": Array [],
},
Object {
"review": Array [],
},
Object {
"review": Array [],
},
Object {
"review": Array [],
},
],
}
hopefully somebody with experience with the Zomato Api can help me out
The way you retrieve & display data is wrong. Check below sample
import React, { Component } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
import axios from 'axios';
export default class Example extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
all_reviews: {}
}
}
async componentDidMount() {
try {
let result = await axios.request({
method: 'GET',
url: "https://developers.zomato.com/api/v2.1/reviews?res_id=16774318",
headers: {
'Content-Type': 'application/json',
'user-key': "af26b7a0e16fb73e6a30ad33cb9c6634",
},
})
this.setState({
isLoading: false,
all_reviews: result.data
})
} catch (err) {
err => console.log(err)
}
}
render() {
return (
<View>
{
this.state.isLoading ?
<View style={{ flex: 1, padding: 20 }}>
<ActivityIndicator />
</View> :
<View>
<Text>REVIEWS:</Text>
{
this.state.all_reviews.user_reviews.length == 0 ?
<View style={{ flex: 1, padding: 20, marginTop: 0 }}>
<Text style={{ color: '#000', fontWeight: 'bold' }}>No reviews for this restaurant yet</Text>
</View> :
<FlatList
keyExtractor={item => item.id}
showsVerticalScrollIndicator={false}
data={this.state.all_reviews.user_reviews}
renderItem={({ item }) =>
<View>
<Text>{item.review.rating}</Text>
</View>}
/>
}
</View>
}
</View>
);
}
}
Change this code according to your requirements & if you have doubts feel free to ask.
Hope this helps you.