Retrieving data from a Text Input and sending it to an api - react-native

I'm working on an application in React Native to experiment with this and I made a bee in Django to retrieve data and send data.
For example, how can I send my data from an input text via a post to django?
For example for get I use something like this
const [todos, setTodos] = useState({});
const todoData = () => {
axios.get('http://192.168.1.5:8000/app/todo-data/')
.then(response => setTodos(response.data))
.catch(error => {
console.error('There was an error!', error);
});
};
React.useEffect(() => {
todoData();
}, []);
My question is how could I put in a "state" what data I want to send?
In Django I want to send this
{
"item":"how to make"
}
I want to send an item with a text as a post
And this is my TextInput
<View style={styles.container}>
<Header />
<View style={styles.header}>
<View style={styles.content}>
<View style={styles.list}>
<TextInput style={styles.textInput} editable maxLength={40}/>
<FlatList data={todos} renderItem={({ item }) => (
<TodoItem item={item} pressHandler={pressHandler} />
)}>
</FlatList>
</View>
</View>
</View>
</View>

To get input value to state you can use TextInput onChange callback.
https://reactnative.dev/docs/textinput#onchange
const [inputValue, setInputValue] = useState(null)
<TextInput
value={inputValue}
onChange={(val) => setInputValue(val)}
/>
Then you can include inputValue in POST request.

Related

how to submit a form in react native and submit to a post api

I want to save the values from all input fields to getdata(), but I am getting undefined value
export default function Signupfor(props) {
// const phoneInput = useRef < PhoneInput > null;
const [text, setTextname] = useState();
function getdata() {
console.log('dsd');
console.log(text);
}
const {userInfo, log} = props?.route?.params;
console.log(log.name);
return (
<View style={styles.prheight}>
<View style={styles.form}>
<Text style={styles.r}>One Last Step</Text>
<TextInput
style={styles.forminput}
label="Name"
value={userInfo.user.name}
onChangeText={text => setTextname(text)}
/>
<TextInput
style={styles.forminput}
label="Email"
value={userInfo.user.email}
onChangeText={text => setTextemail(text)}
/>
<TextInput
style={styles.forminput}
label="Whatsapp Number"
keyboardType="numeric"
value={userInfo.user.number}
onChangeText={text => setTextnumber(text)}
// value={this.state.myNumber}
maxLength={10} //setting limit of input
/>
</View>
<View style={styles.buttonw}>
<Button color="#7743DB" title="Lets Go" onPress={() => getdata()} />
</View>
</View>
);
}
Here, name and email should not be able to be edited. I want to pass the value from value={userInfo.user.name} to the getdata()
you can use formik package for making form in react native
Installation
yarn add formik
Usage
import { Formik } from "formik";
export default function Signupfor(props) {
const { userInfo, log } = props?.route?.params;
console.log(log.name);
return (
<Formik
initialValues={{
name: userInfo.user.name,
email: userInfo.user.email,
number: userInfo.user.number,
}}
onSubmit={async (values, actions) => {
try {
console.log("name", values.name);
console.log("phone", values.number);
const params = {
full_name: values.name,
email: values.email,
phone_number: values.number,
};
} catch (error) {
let message = error.message;
console.log(message)
} finally {
actions.setSubmitting(false);
}
}}
>
{({
handleChange,
setFieldValue,
handleSubmit,
values,
errors,
touched,
isSubmitting,
}) => (
<View style={styles.prheight}>
<View style={styles.form}>
<Text style={styles.r}>One Last Step</Text>
<TextInput
style={styles.forminput}
label="Name"
value={values.name}
onChangeText={handleChange("name")}
/>
<TextInput
style={styles.forminput}
label="Email"
value={values.email}
onChangeText={handleChange("email")}
/>
<TextInput
style={styles.forminput}
label="Whatsapp Number"
keyboardType="numeric"
value={values.number}
onChangeText={handleChange("number")}
// value={this.state.myNumber}
maxLength={10} //setting limit of input
/>
</View>
<View style={styles.buttonw}>
<Button
color="#7743DB"
title="Lets Go"
onPress={() => handleSubmit()}
/>
</View>
</View>
)}
</Formik>
);
}
Your original method doesn't populate the state unless you edit the text input field, this is because your initialState doesn't have a value to start with. so firing getData() is reading empty state if the fields havent been changed.
onChangeText={text => setTextname(text)}
Only fire if you edit the textInput field.
Also I think you might be missing props, so first check if you are getting the correct data from props by logging it.
Once you have confirmed the props are available.
Set the initialState for name to userInfo.user.name
const { userInfo } = props?.route?.params;
const [name, setName] = useState(userInfo.user.name);
Then pass the state name to your TextInput and it should populate the value by reading from state.
return (
<>
<TextInput
placeholder="name"
value={name}
onChangeText={(text) => setName(text)}
/>
<Button title="Submit" onPress={() => getData()} />
</>
)
Make sure to create states for any additional values you wish to save.
const [name, setName] = useState(userInfo.user.name);
const [email, setEmail] = useState(userInfo.user.email);
You can use a library like https://react-hook-form.com to check an example with react native on video.
Or you can right it yourself, in the example below any time you need access to input values you can read it from text and number
const UselessTextInput = () => {
const [text, onChangeText] = useState("Useless Text");
const [number, onChangeNumber] = useState(null);
return (
<SafeAreaView>
<TextInput
style={styles.input}
onChangeText={onChangeText}
value={text}
/>
<TextInput
style={styles.input}
onChangeText={onChangeNumber}
value={number}
placeholder="useless placeholder"
keyboardType="numeric"
/>
</SafeAreaView>
);
};
You can do something like this!!
export default function Signupfor(props) {
const {userInfo, log} = props?.route?.params;
const [name, setName] = useState(userInfo?.user?.name);
const [phone, setPhone] = useState(userInfo?.user?.number);
function getdata() {
console.log("name",name)
console.log("phone",phone)
}
return (
<View style={styles.prheight}>
<View style={styles.form}>
<Text style={styles.r}>One Last Step</Text>
<TextInput
style={styles.forminput}
label="Name"
// this value must be same with useState
value={name}
onChangeText={text => setName(text)}
/>
<TextInput
style={styles.forminput}
label="Mobile"
value={phone}
onChangeText={text => setPhone(text)}
/>
</View>
<View style={styles.buttonw}>
<Button color="#7743DB" title="Lets Go" onPress={() => getdata()} />
</View>
</View>
);
}
Same goes for email.

Error: Objects are not valid as a React child (found: [object Error]). If you meant to render a collection of children, use an array instead

When i try to integrate with mutation using apollo i got this error Objects are not valid as a React child (found: [object Error]). If you meant to render a collection of children, use an array instead react native
src/Mutation
```
export const SIGNIN_USER = gql `
mutation signinUser($usersignin:UserSigninInput!) {
user:signinUser(userSignin:$usersignin) {
token
}
}
`
```
src/Login.js
const Login = (props) => {
const [values, setValues] = useState({ email: '', password: '' });
const [signinUser,{error,loading,data}] = useMutation(SIGNIN_USER)
if (loading) return <Text>Loading... 🚀</Text>
if (error) return <Text>{error}</Text>
const handleChange = (name, value) => {
setValues({
...values,
[name]: value,
});
};
const handleSubmit = () => {
console.log("values are ==>",values)
signinUser({
variables: {
userSignin: values
}
})
}
return (
<View style={styles.container}>
<View style={styles.titleView} >
<Text style={styles.title}>Login</Text>
</View>
<View style={{ height: hp('5%') }}></View>
<TextInput placeholder='Please Enter Email' style={styles.textInput} onChangeText={(text) => handleChange('email', text)}
value={values.firstName} />
<TextInput secureTextEntry={true} placeholder='Please Enter Password' style={styles.textInput} onChangeText={(text) => handleChange('password', text)} />
<TouchableOpacity style={styles.buttonView} onPress={handleSubmit} >
<Text style={styles.btnText}>Signin</Text>
</TouchableOpacity>
</View>
)
}
Error: Objects are not valid as a React child (found: [object Error]). If you meant to render a collection of children, use an array instead What is wrong in my code ?Error: Objects are not valid as a React child (found: [object Error]). If you meant to render a collection of children, use an array instead
The value should be value={values.email} like this:
<TextInput
placeholder='Please Enter
Email' style={styles.textInput}
onChangeText={(text) =>
handleChange('email', text)}
value={values.email}
/>

Why ther's no display even when i have items react native

I'm trying to build an history page that request data from async storage and display it on the screen
this is my code
function History() {
let [items, setItems] = useState([])
useEffect(() => {
AsyncStorage.getItem("users").then(users => {
setItems(users.split("*"))
})
}, []);
return (
<View>
<ScrollView style={styles.container}>
{items.map((item, index) => {
<View key = {index} style = {styles.item}>
<Image
style={styles.stretch}
source={require('../assets/logo.png')}
/>
<Text style={styles.Title}>{item.name}</Text>
<Text style={styles.number}>+21644987156</Text>
</View>
})}
</ScrollView>
</View>
)
}
there's many items in the async storage and no display

React Native JSON issue with YouTube Data v3 API call

I have a request pulling in from YouTube, to create a list of videos I want to display in a flatlist. I use the same approach across the application (calling WordPress, etc...), but when Im trying to achieve the same with the YouTube API (I've got the key setup etc..), it throws an error;
const Watch = ({typeOfProfile}) => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
let x = {foo: 11, bar: 42};
function playertype(val) {
return 'https://www.googleapis.com/youtube/v3/searchpart=snippet&channelId=UCa_6KiOjxm6dEC_mMRP5lGA&maxResults=20&order=date&type=video&key=xxxxx';
}
useEffect(() => {
fetch(playertype(typeOfProfile))
.then((response) => response.json())
.then((json) => {
x = setData(json)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
const result = Object.keys(x).map(key => ({[key]: x[key]}));
return (
<View style={styles.body}>
<View style={styles.topscroll}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={result}
horizontal={true}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<View>
<Text>
{x.val}
</Text>
</View>
)}
/>
)}
</View>
</View>
);
};
Someone mentioned it could be an object being returned instead of an array, seems odd the json structure is the same as other requests I use this approach for.
I discovered that I had to add brackets on the data property of the FlatList. So instead of
data={data}
I had to change it too;
data={[data]}
Code now;
<FlatList
data={[data]}
horizontal={true}
keyExtractor={({ id }, index) => id}
renderItem={({ item, index }) => (
<View style={styles.container}>
<Image style={styles.imgyoutubeprev} source={{ uri: chkValue(item.items[0].snippet.thumbnails.high.url) }} />
</View>
)}
/>

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>