expecting newline or semicolon + unexpected token after function name - react-native

I have the following code:
export default class HomeScreen extends Component {
state = {text: ''};
_onPressSearch() {
Alert.alert("Button pressed!")
}
function getCitiesListFromApiAsync() {
return fetch("https://samples.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=b6907d289e10d714a6e88b30761fae22.json")
.then((response) => response.json())
.then((responseJson) => {
return responseJson.list;
})
.catch((error) => {
Alert.alert("Error while loading: " + error);
})
}
render() {
return (<View style={styles.container}>
<ScrollView style={styles.scrollViewContainer} contentContainerStyle={styles.contentContainer}>
<View style={styles.searchContainer}>
<TextInput placeHolder="Type something!" onChangeText={(text) => this.setState({text})}
value={this.state.text}/>
</View>
<TouchableOpacity
onPress={this._onPressSearch}>
<View>
<Text>Search</Text>
</View>
</TouchableOpacity>
<View style={styles.container}>
<FlatList
data={this.getCitiesListFromApiAsync()}
renderItem={({item}) => <Text style={styles.item}>{item.name}</Text>}
/>
</View>
</ScrollView>
</View>);
}
}
Now I am trying to get data from server, parse it and add it to flatlist. I get data from this API: https://samples.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=b6907d289e10d714a6e88b30761fae22.json. I created a special function for it, the same as in tutorial. But my IDE (Webstorm) marks it in red and writes that there should be a newline or semicolon after function name and when I run the app I have the following error:
Failed building JavaScript bundle.
SyntaxError: /Users/siarhei.mikhaylouski/WebstormProjects/WeatherApp/screens/HomeScreen.js: Unexpected token (23:13)
function getCitiesListFromApiAsync() {
| ^
24 | return fetch("https://samples.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=b6907d289e10d714a6e88b30761fae22.json")
25 | .then((response) => response.json())
26 | .then((responseJson) => {
What's the matter and how can I solve it?

You should not use the function keyword when you define a method inside a class.
Just write:
getCitiesListFromApiAsync() {
// [...]
}

Related

React useState hooks not updating render Text

I'm using hooks to print a list of conversations, with the name of the contact and the last message for each.
I'm using an interval to check for each conversation if the last message has changed. It's working find with the API, I get the content and use setState to change it, but when I try to get it in the render part, I get the old one.
Here is some code:
const _getMessages = () => {
setDataMsg('');
if (dataContacts) {
dataContacts.map((itemValue, itemIndex) => {
ApiClient.instance.getConversation(itemValue.id).then(response => {
if (response.status === 200) {
setDataMsg([...dataMsg, response.data[response.data.length-1].content]);
console.log('getting all messages ', response.data[response.data.length-1].content);
}
}).catch(error => {
console.log(error);
Alert.alert('Erreur', 'Impossible de récupérer les messages')
})
})
}
else
clearInterval(intervalMsg);
if (props.navigation.state.routeName !== "MessagesPage") {
clearInterval(intervalMsg);
}
}
// Affichage du dernier message //
const _showMessage = (index) => {
if (dataMsg) {
return (dataMsg[index]);
}
return ('Aucun message');
}
And the render:
<FlatList
style={getStyle().messageList}
data={dataContacts}
extraData={dataMsg}
refreshing={true}
keyExtractor={(item) => {
return item.id.toString();
}}
renderItem={({item, index}) => {
return (
<TouchableOpacity
style={getStyle().card}
onPress={() => {
cardClickEventListener(item)
}}>
<View style={getStyle().cardImage}>
<Image style={getStyle().image}
source={_handleImg(item)}/>
</View>
<View style={getStyle().cardContent}>
<Text
style={[getStyle().name, {fontFamily: props.font}]}>{item.firstName + " " + item.lastName}</Text>
<Text
style={{fontFamily: props.font, fontStyle:'italic'}}>{_showMessage(index)}</Text>
</View>
<View style={getStyle().cardIndicator}>
</View>
</TouchableOpacity>
)
}}/>

fetch API call in react native is not working when I load the screeen

I have made an App in react native. My app makes API calls to my webserver and then Displays information based on that. The problem Is when I first load this screen... I get the loading screen and the information is display in the way it is supposed to but when I leave the screen and then comeback to the screen, it shows nothing and my array containing the items is empty, hence I think I am having problems with the API call when I leave the screen and then come back.
I am using React navigation 5 in My App.
export default function ({ navigation }) {
const [openQueries, setOpenQueries] = useState([]);
const [isLoading, seIsLoading] = useState(true);
const open_queries = [];
function getOpenQueries() {
var retrieveData = async () => {
try {
var value = await AsyncStorage.getItem("user");
var data = JSON.parse(value);
return data.user._id;
} catch (error) {
alert(error);
}
};
retrieveData().then((user) => {
fetch(URL + "/api/contact/open_queries", {
method: "POST",
body: "user=" + user + "&status=open",
headers: { "Content-type": "application/x-www-form-urlencoded" },
})
.then((response) => {
return response.json();
})
.then((responseJson) => {
if (responseJson.error === null) {
setOpenQueries(responseJson.open_queries);
seIsLoading(false);
}
});
});
}
getOpenQueries();
openQueries.forEach((query) => {
open_queries.push(
<TouchableOpacity
onPress={() =>
navigation.navigate("Chat", {
id: query._id,
title: query.title,
query: query,
showInput: true,
})
}
>
<View style={styles.inboxItem}>
<Text style={styles.inboxTitle}>{query.title}</Text>
<Text style={styles.inboxSubtext}>
{query.chats[query.chats.length - 1].chat}
</Text>
<View style={styles.lineBreak}></View>
</View>
</TouchableOpacity>
);
});
return (
<SafeAreaView style={styles.container}>
<Text style={styles.title}>Contacts</Text>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate("NewQuery")}
>
<Text style={styles.text}>Start a new query</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate("ClosedQueries")}>
<View style={styles.button}>
<Text style={styles.text}>Closed Queries</Text>
</View>
</TouchableOpacity>
<Text style={styles.subTitle}>Open Queries</Text>
{isLoading ? (
<View style={styles.loader}>
<Code />
</View>
) : (
<ScrollView style={{ paddingTop: 10 }}>
{openQueries.length > 0 ? (
open_queries
) : (
<Text style={styles.noQuery}>No Open Queries found</Text>
)}
</ScrollView>
)}
<ScrollView></ScrollView>
<BottomNavigation navigation={navigation} active={"contact"} />
</SafeAreaView>
);
}
Try this way
export default function ({ navigation }) {
const [openQueries, setOpenQueries] = useState([]);
const [isLoading, seIsLoading] = useState(true);
const [open_queries_views, setOpenQueriesViews] = useState([]);
function getOpenQueries() {
....
}
// Similar to componentDidMount
useEffect(() => {
getOpenQueries();
});
function renderViews(){
const open_queries = [];
openQueries.forEach((query) => {
open_queries.push(
<TouchableOpacity> ... </TouchableOpacity>
);
});
setOpenQueriesViews(open_queries); // set state here to auto reflect on view
}
return (
<SafeAreaView style={styles.container}>
....
<ScrollView style={{ paddingTop: 10 }}>
{open_queries_views.length > 0 ? (
open_queries_views
) : (
<Text style={styles.noQuery}>No Open Queries found</Text>
)}
</ScrollView>
.....
</SafeAreaView>
);
}

Using parameter that would fetch data from another api based on a condition react native?

I have two pages Portfolio.js and PortfolioDetails.js. In the Portfolio.js file, I am fetching data from my api and displaying all the portfolios in a list. When I click on portfolio, it should take me to the PortfolioDetails screen, which will display only those stocks from stock api which are in the portfolio.
e.g if I click on Portfolio with id 1, it should filter out stocks from stock api which has portfolio id 1 and display all those stocks on the screen.
So far, I am successful in fetching both the apis and also when I click on one portfolio, it passes the portfolio id parameter to my PortfolioDetails screen. I am stuck where I have to filter the stocks to display based on this passed parameter - id.
Portfolio.js file
export default class Portfolio extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
title: "Portfolio",
header: null,
};
};
constructor(props) {
super(props);
this.state = {
loading: true,
PortfolioSource: []
};
}
componentDidMount() {
fetch("http://127.0.0.1:8000/portfolios/")
.then(response => response.json())
.then((responseJson) => {
this.setState({
loading: false,
PortfolioSource: responseJson
})
})
.catch(error => console.log(error)) //to catch the errors if any
}
FlatListItemSeparator = () => {
return (
<View style={{
height: .5,
width: "100%",
backgroundColor: "rgba(0,0,0,0.5)",
}}
/>
);
}
renderItem = (data) =>
<TouchableOpacity style={styles.list} onPress={() => this.props.navigation.push('Details', { portid: data.item.id })} >
<Text style={styles.lightText}>{data.item.id}</Text>
<Text style={styles.lightText}>{data.item.portfolio_id}</Text>
<Text style={styles.lightText}>{data.item.name}</Text>
<Text style={styles.lightText}>{data.item.description}</Text>
<Text style={styles.lightText}>{data.item.gains}</Text></TouchableOpacity>
render() {
if (this.state.loading) {
return (
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9" />
</View>
)
}
return (
<View style={styles.container}>
<FlatList
data={this.state.PortfolioSource}
ItemSeparatorComponent={this.FlatListItemSeparator}
renderItem={item => this.renderItem(item)}
keyExtractor={item => item.id.toString()}
/>
</View>
)
}
}
PortfolioDetails.js
export default class PortfolioDetails extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
title: "PortfolioDetails",
header: null,
};
};
constructor(props) {
super(props);
this.state = {
loading: true,
PortfolioDetailsdataSource: [],
};
}
componentDidMount() {
fetch(`http://127.0.0.1:8000/stocks/`)
.then(response => response.json())
.then((responseJson) => {
this.setState({
loading: false,
PortfolioDetailsdataSource: responseJson
})
})
.catch(error => console.log(error)) //to catch the errors if any
}
FlatListItemSeparator = () => {
return (
<View style={{
height: .5,
width: "100%",
backgroundColor: "rgba(0,0,0,0.5)",
}}
/>
);
}
goToPrevScreen = () => {
this.props.navigation.goBack();
}
renderItem = (data) =>
<TouchableOpacity style={styles.list}>
<Text style={styles.lightText}>{data.item.id}</Text>
<Text style={styles.lightText}>{data.item.ticker}</Text>
<Text style={styles.lightText}>{data.item.price}</Text>
<Text style={styles.lightText}>{data.item.market_cap}</Text>
<Text style={styles.lightText}>{data.item.YTD}</Text>
<Text style={styles.lightText}>{data.item.OneYear}</Text>
<Text style={styles.lightText}>{data.item.TwoYear}</Text>
<Text style={styles.lightText}>{data.item.TTM_Sales_Growth}</Text>
<Text style={styles.lightText}>{data.item.PE_Ratio}</Text>
</TouchableOpacity>
render() {
if (this.state.loading) {
return (
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9" />
</View>
)
}
return (
<View style={styles.container}>
<FlatList
data={this.state.PortfolioDetailsdataSource}
ItemSeparatorComponent={this.FlatListItemSeparator}
renderItem={item => this.renderItem(item)}
keyExtractor={item => item.id.toString()}
/>
<Text> portid: {this.props.navigation.state.params.portid} </Text>
<Button
onPress={() => this.goToPrevScreen()}
title="go back to Portfolio"
/>
</View>
)
}
}
You can use .find(). For example:
PortfolioDetailsDataSource.find(item => item.id === this.props.navigation.state.params.portId)
Assuming IDs are unique, this will return the desired object, otherwise it will return the first occurrence that passes the condition.

Display data as simple line graph - react native

i want to display the data as line graph instead of text.
i used react-native-charts-wrapper for graph please help me out
.then(res => res.json())
.then(res => {
console.log(`res: ${JSON.stringify(res['activities-distance'])}`);
this.setState({
result:res['activities-distance']});
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>All-Day Activity</Text>
<Button title="CHECK STEPS" onPress{()=>this.connectFitbit()}/>
<FlatList
data={this.state.result}
renderItem={
({item}) => <View>
<Text>DATE : {item.dateTime}</Text>
<Text>STEPS :{item.value}</Text>
</View>
}
keyExtractor={(item, index) => {return index+item}}/>
</View>

View inside curly braces not showing

I'm new in ReactNative. I'm following a tutorial from Udemy. I've been trying to show a value from a variable. its working in the instructor's video but not in my code. the code is given below:
export default class App extends React.Component {
state = {
placeName: '',
places: []
}
placeNameChangedHandler = val => {
this.setState({
placeName: val
})
}
placeSubmitHandler = () => {
if (this.state.placeName.trim() === "") {
return;
}
this.setState(prevState => {
return {
places: prevState.places.concat(prevState.placeName)
}
})
}
render() {
const placesOutput = this.state.places.map(place => {
<Text>{place}</Text>
})
return (
<View style={styles.container}>
<View style={styles.inputContainer}>
<TextInput
placeholder="Type something"
style={styles.placeInput}
value={this.state.placeName}
onChangeText={this.placeNameChangedHandler}/>
<Button
style={styles.placeButton}
onPress={this.placeSubmitHandler}
title="Add"/>
</View>
<View>
{this.placesOutput}
</View>
</View>
);
}
}
but the {placeOutput} is not showing anything. its working in the instructor's video but not in my code. What am I doing wrong?
You aren't returning anything in your map() function. Your render function should look like this:
render() {
const placesOutput = this.state.places.map(place => {
return <Text>{place}</Text> //Added return statement
})
return (
<View style={styles.container}>
<View style={styles.inputContainer}>
<TextInput
placeholder="Type something"
style={styles.placeInput}
value={this.state.placeName}
onChangeText={this.placeNameChangedHandler}/>
<Button
style={styles.placeButton}
onPress={this.placeSubmitHandler}
title="Add"/>
</View>
<View>
{this.placesOutput}
</View>
</View>
);
}
All I did was add a return statement in your this.state.places.map() function.