How to store API response in state And pass this response value to another screen as params in react native - react-native

I am new to react native. I have created A screen. Where I am getting response from API. but now I want to store that response in state. and I want to send that value to another screen by navigation params.
my response is like this ->
Array [
Object {
"phpid": 10,
},
]
here is my code
constructor(props) {
super(props);
this.state={
};
}
fetch('https://xuz.tech/Android_API_CI/uploaddata/t_details?query=', {
method: 'POST',
headers: {'Accept': 'application/json, text/plain, */*', "Content-Type": "application/json" },
body: JSON.stringify([{"==some values=="}])
})
.then((returnValue) => returnValue.json())
.then(function(response) {
console.log(response)
return response.json();
render(){
return (
<View style={{flex: 1}}>
color="black" onPress={() => this.props.navigation.navigate("FormItems",{i want to send value to formitems})} />
</View>
)}

Set your state once you receive your response, then use your state as params when navigating. Once your fetch has been resolved:
this.setState({ response: response.json() });
Sending params to another screen is fairly simple, you just need to pass an object as the second parameter to navigate.
this.props.navigation.navigate('FormItems', {
form: this.state.response,
});
The receiving component will then need to read those params:
class DetailsScreen extends React.Component {
render() {
const { navigation } = this.props;
return (
<Text>{JSON.stringify(navigation.getParam('form', 'some default'))}</Text>
}
}
A full explanation on how to use params with react-navigation v4 can be found here: https://reactnavigation.org/docs/4.x/params

Use it like this. first initialise the state and when you get data from api set the data in state and when button press pass the data to new screen in params.
import React, { Component } from 'react';
import { Text, View } from 'react-native';
export default class Example extends Component {
state = {
data: [], // initialize empty state
};
componentWillMount() {
this.requestData();
}
requestData = () =>{
fetch('https://xuz.tech/Android_API_CI/uploaddata/t_details?query=', {
method: 'POST',
headers: {'Accept': 'application/json, text/plain, */*', "Content-Type": "application/json" },
body: JSON.stringify([{"==some values=="}])
})
.then((returnValue) => returnValue.json())
.then(function(response) {
this.setState({
data:response //set data in state here
})
})
}
render() {
return (
<View style={{ flex: 1 }}>
<Button
color="black"
onPress={() =>
this.props.navigation.navigate('FormItems', {
data: this.state.data, // pass data to second screen
})
}
/>
</View>
);
}
}

Related

How Can I Use a Component by Functions Response in React Native?

I'm trying to show a Lottie animation if the API response true. Here is my code:
export default class Register extends Component{
constructor(props){
super(props);
this.state = {
//variables
};
}
buttonClick = () =>{
//variables
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({variables})
};
fetch('api_url',requestOptions)
.then((response) => { return response.json() } )
.catch((error) => console.warn("fetch error:", error))
.then((response) => {
console.log(response)
if(response == "true"){
<LottieView
style={styles.success}
source = {require("./lottie/success.json")}
autoPlay = {true}
loop={false}
/>
}
})
}
render(){
return (
//textinputs and buttons
)
}
}
but the animation not showing up. I know it because of LottieView not in "render and return" parts but I don't know how can I fix it.
Add a useState isFetched, default value is false. If response is true, change state to true.
In render add this:
isFetched && (
<LottieView
style={styles.success}
source = {require("./lottie/success.json")}
autoPlay = {true}
loop={false}
/>
)

navigation.getParam is not a function. (In 'navigation.getParam('message', 'hiiii')', 'navigation.getParam' is undefined) in react native

I am new to react native. I want to send API data from one screen to another screen And want to display that data on that screen. but I am getting error like = navigation.getParam is not a function. (In 'navigation.getParam('message', 'hiiii')', 'navigation.getParam' is undefined). please help , thanks.
here is my first screen code from where I send data
class Browse extends Component {
constructor(props) {
super(props);
this.state = {
ListView:[]
};
}
state = {
categories: [],
error: [],
};
ListView () {
const {navigation} = this.props
AsyncStorage.multiGet(["application_id", "created_by"]).then(response => {
console.log(response[0][1]) // Value1
console.log(response[1][1]) // Value2
fetch("https://xys.tech/Android_API_CI/get_lead_data_for_user", {
method: "POST",
headers: { 'Accept': 'application/json, text/plain, */*', "Content-Type": "application/json" },
body: JSON.stringify([{ id:response[1][1], application_id:response[0][1]}]),
})
.then((returnValue) => returnValue.json())
.then((response) => {
alert(JSON.stringify(response))
this.props.navigation.navigate("ListView", {
message: "hiiiii",
});
})
here is my second screen code where I want to show API data
const { width } = Dimensions.get("window");
class Browse extends Component {
constructor(props) {
super(props);
this.state ={
Email:"",
}
render() {
const { profile, navigation } = this.props;
const tabs = [""];
const ListView = navigation.getParam('message','hiiii')
//const route = this.props
return (
<View style={{flex: 1}}>
<ScrollView>{ListView}</ScrollView>
</View>
);
}
}
Try with route like this
this.props.route.params.message

Displaying multiple data in react native

I am pretty new to react native. I am currently grabbing data from my node.js and trying to show all the data I grabbed into my View. In react.js, i did
documnet.getElementById.append().
What is the best way to do it in react native?
my code looks something like this
class GlobalRankings extends Component{
constructor(){
super();
this.state = {
}
this.getGlobalRankings();
}
getGlobalRankings(){
var request = new Request(checkEnvPort(process.env.NODE_ENV) + '/api/global_rankings', {
method: 'GET',
headers: new Headers({ 'Content-Type' : 'application/json', 'Accept': 'application/json' })
});
fetch(request).then((response) => {
response.json().then((data) => {
console.log(data);
for (var i in data.value){
console.log(data.value[i]); //where i grab my data
}
});
}).catch(function(err){
console.log(err);
})
}
render(){
return(
<View style={styles.container}>
// want my data to be here
</View>
)
}
}
Thanks for all the help
You can make an array in state in constructor, this.state = { arr: [] }
Then you assign the data array you get from the response.
fetch(request).then((response) => {
response.json().then((data) => {
this.setState({ arr: data.array });
});
}).catch(function(err){
console.log(err);
});
Then in the component body,
<View style={styles.container}>
{
this.state.arr.map((value, index) => {
return(
<Text key={index}>{value.text}</Text>
);
})
}
</View>

React Native getting collections from Zomato API

I am trying to get collections from Zomato API (https://developers.zomato.com/documentation) and I am trying to retrieve the collections list and display them onto a flatList. However every time I try to retrieve it my terminal seems to output undefined
Here is my code
async componentDidMount(){
try {
const res = await axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/collections`,
headers: {
'Content-Type': 'application/json',
'user-key': 'a31bd76da32396a27b6906bf0ca707a2'
},
params: {
'city_id': `${this.state.loca}`
}
});
this.setState({ data: res.data });
console.log(res.data.collections.title)
} catch (err) {
console.log(err);
} finally {
this.setState({ isLoading: false });
}
};
when I console.log(res.data.collections) I get the entire list of all components within the collections Array from the API. However when I try to access the title component; the terminal outputs undefined
what am I doing wrong?
Do check out the below code, i think there was a small problem with your code, you were not extracting the exact data. Ive corrected it by displaying the title of restuarent. you can do more. expo link is as expo-link
import React from 'react';
import {
View,
Text,
FlatList,
StyleSheet,
TouchableHighlight,
Dimensions,
Image,
} from 'react-native';
import Modal from 'react-native-modal';
import { createAppContainer } from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import { Card, Icon, Button } from 'react-native-elements';
import Constants from 'expo-constants';
// import {apiCall} from '../src/api/Zomato';
// import Logo from '../assets/Logo.png';
import axios from 'axios';
export default class HomeScreen extends React.Component {
constructor(props){
super(props);
// this.navigate = this.props.navigation.navigate;
this.state={
data : [],
isModalVisible: false,
loca: 280
}
}
async componentDidMount(){
try {
const res = await axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/collections`,
headers: {
'Content-Type': 'application/json',
'user-key': 'a31bd76da32396a27b6906bf0ca707a2'
},
params: {
'city_id': `${this.state.loca}`
}
});
// alert(res.data.collections, 'response');
this.setState({ data: res.data.collections });
} catch (err) {
console.log(err);
} finally {
}
}
render() {
return (
<View>
<FlatList
style={{marginBottom: 80}}
keyExtractor={item => item.id}
data={this.state.data}
renderItem={({ item }) =>
<TouchableHighlight onPress={()=> this.props.navigation.navigate('CategoryScreen', { category: item.categories.id, city: this.state.loca })}>
<Card>
<Text style={{color:'#000',fontWeight:'bold'}}>{item.collection.title} </Text>
</Card>
</TouchableHighlight>}
/>
</View>
);
}
}
do revert if any doubts, ill clear it. hope it helps;
Axios returns a promise try keeping the setState in .then and stop trusting console.log
axios.request({
method: 'get',
url: `https://developers.zomato.com/api/v2.1/collections`,
headers: {
'Content-Type': 'application/json',
'user-key': 'a31bd76da32396a27b6906bf0ca707a2'
},
params: {
'city_id': `${this.state.loca}`
}
}).then( res => this.setState({res}))

Why isn't mailchimp API working with fetch?

I'm trying to add an email address to a mailchimp list I have.
This is for a react native app and I'm trying to implement the request using fetch.
This is my code within the component:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { connect } from 'react-redux';
import { emailChanged, nameChanged, addToWaitingList } from '../actions';
import { Card, CardSection, Input, Button, Spinner } from '../components/Auth';
class addToWaitingListForm extends Component {
onEmailChange(text) {
this.props.emailChanged(text);
}
onButtonPress() {
const { email } = this.props;
this.props.addToWaitingList({ email });
}
renderButton() {
if (this.props.loading) {
return <Spinner size="large" />;
}
return (
<Button onPress={this.onButtonPress.bind(this)}>
Keep me in the loop!
</Button>
);
}
render() {
return (
<View>
<Card>
<CardSection>
<Input
placeholder="your name"
onChangeText={this.onNameChange.bind(this)}
value={this.props.name}
/>
</CardSection>
<CardSection>
<Input
placeholder="email#uni.ac.uk"
onChangeText={this.onEmailChange.bind(this)}
value={this.props.email}
/>
</CardSection>
<Text style={styles.errorTextStyle}>
{this.props.error}
</Text>
<CardSection style={{ borderBottomWidth: 0 }}>
{this.renderButton()}
</CardSection>
</Card>
</View>
);
}
}
const mapStateToProps = ({ auth }) => {
const { email, name, error, loading } = auth;
return { email, name, error, loading };
};
export default connect(mapStateToProps, {
emailChanged,
addToWaitingList
})(addToWaitingListForm);
Add this is my action code for interacting with the mailchimp api:
import Router from '../../navigation/Router';
import { getNavigationContext } from '../../navigation/NavigationContext';
export const addToWaitingList = ({ email }) => {
const emailListID = 'e100c8fe03';
fetch(`https://us13.api.mailchimp.com/3.0/lists/${emailListID}/members/`, {
method: 'POST',
body: JSON.stringify({
'email_address': email,
'status': 'subscribed',
'merge_fields': {
'FNAME': 'Urist',
'LNAME': 'McVankab'
}
})
})
.then(() => addSubscriberSuccess())
.catch(error => console.log(error));
};
const addSubscriberSuccess = () => {
getNavigationContext().getNavigator('root').immediatelyResetStack([Router.getRoute('auth')]);
};
Right now, the error I'm just getting back is ExceptionsManager.js:62 Cannot read property 'type' of undefined and Error: unsupported BodyInit type
What does this mean and how can I fix this?
You need to do two things.
First off you need to send the basic authentication via fetch so you cant do "user:pass" You have to convert it with btoa('user:pass').
Then you have to send it with mode: 'no-cors'
let authenticationString = btoa('randomstring:ap-keyxxxxxxx-us9');
authenticationString = "Basic " + authenticationString;
fetch('https://us9.api.mailchimp.com/3.0/lists/111111/members', {
mode: 'no-cors',
method: 'POST',
headers: {
'authorization': authenticationString,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email_address: "dude#gmail.com",
status: "subscribed",
})
}).then(function(e){
console.log("fetch finished")
}).catch(function(e){
console.log("fetch error");
})