does anyone have an example of a default value used in the library react-native-dropdown-picker used hooks e function, or another libre that makes this msm function simpler.
export default function OrphanageData() {
const [date, setDate] = useState(new Date())
const [value, setValue] = useState();
const [items, setItems] = useState([{}]);
let controller;
return (
<>
<StatusBar backgroundColor="#15c3d6"/>
<ScrollView style={styles.container} contentContainerStyle={{ padding: 24 }}>
<Text style={styles.title}>Compras</Text>
<Text style={styles.label}> ID - Brinco</Text>
<TextInput
style={styles.input}
/>
<DropDownPicker
items={items}
controller={instance => controller = instance}
onChangeList={(items, callback) => {
new Promise((resolve, reject) => resolve(setItems(items)))
.then(() => callback())
.catch(() => {});
}}
defaultValue={value}
onChangeItem={item => setValue(item.value)}
/>
<RectButton style={styles.nextButton} onPress={() => {}}>
<Text style={styles.nextButtonText}>Cadastrar</Text>
</RectButton>
</ScrollView>
</>
)
}
This might help (Using Hooks)
export default function OrphanageData() {
const [value, setValue] = useState('usa');
const [items, setItems] = useState([
{label: 'USA', value: 'usa'},
{label: 'UK', value: 'uk'},
{label: 'France', value: 'france'},
]);
return(
<DropDownPicker
items={items}
defaultValue={value}
onChangeItem={item => setValue(item.value)}
.....
/>
);
}
Related
Console logging my react native app shows the data I fetch from an API. The problem now is that it is not displaying in the FlatList.
const HealthLinkMain = () => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(API_URL, {
method: "GET",
headers: {
Authorization: `Bearer ${TOKEN}`,
},
});
setData(response.data)
} catch (error) {
console.error(error);
}
};
fetchData();
}, []);
return (
<View style={styles.container}>
<Text>Test</Text>
<FlatList
data={data.data}
renderItem={(item) => (
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)}
keyExtractor={(item, index) => item.clinic_name}
/>
</View>
);
};
I think the problem might be in your renderItem as you haven't destructured the item, try this:
renderItem = {({ item }) => {
return (
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)
}}
You can also seperate it the renderItem into a function of it's own which a lot of people tend to do:
const renderItem = ({item}) => {
return(
<View>
<Text>{item.clinic_name}</Text>
<Text>{item.clinic_address}</Text>
</View>
)
}
and then change the flatlist calling function accordingly:
<FlatList
data={data.data}
renderItem={renderItem}
keyExtractor={(item, index) => item.clinic_name}
/>
I want to dynamically render the data when filtering from start to end. The logic only displays one date value at a time. I want to display the E_NodeB Cell_Name Date E_RAB_Setup_Success_Rate Data_Traffic_DL Data_Traffic_UL UL_Throughput when I filter the from and to dates
`const data = "http://localhost:8080/sites";
const SelectSingle = () => {
var traffic = [];
var rab = [];
var newData = [];
const [sites, setsites] = useState([]);
const [selectedSite, setSelectedSite] = useState([]);
const [startDate, setDate] = useState();
const [endDate, setEndDate] = useState();
// 1
const handleChange = (event) => {
event.preventDefault();
const siteSelected = event.target.value;
const itemSelected = sites.filter(
(site) => site.Cell_Name === siteSelected
);
setSelectedSite(itemSelected);
};
// Start Date
// Traffice_Date
const handleDate = (e) => {
e.preventDefault();
const siteSelected = "4G_ADONKIA-2";
const dateChosen = sites.filter((site) => {
return (
site.Traffice_Date === getDate(e) && site.Cell_Name === siteSelected
);
});
newData.push(dateChosen);
setSelectedSite(dateChosen);
};
// End date
const handleEndDate = (e) => {
e.preventDefault();
const siteSelected = "4G_ADONKIA-2";
const dateChosen = sites.filter((site) => {
return (
site.Traffice_Date === getDate(e) && site.Cell_Name === siteSelected
);
});
setSelectedSite(dateChosen);
};
// Get Date Function
const getDate = (e) => {
const start = e.target.value;
const [year, month, day] = start.split("-");
const newDate = `${day}/${month}/${year}`;
return newDate;
};
useEffect(() => {
fetch(data)
.then((res) => res.json())
.then((data) => setsites(data));
});
selectedSite.map((site) => {
rab.push(site.E_RAB_Setup_Success_Rate);
traffic.push(site.Traffice_Date);
});
const state = {
labels: traffic,
datasets: [
{
label: "E_RAB_Setup_Success_Rate",
backgroundColor: "rgba(75,192,192,1)",
borderColor: "rgba(0,0,0,1)",
borderWidth: 2,
data: rab,
},
],
};
return (
<div>
<div className="data-class">
<select
onChange={(e) => {
handleChange(e);
}}
>
{sites.map((site, index) => (
<option value={site.Cell_Name} key={index}>
{site.Cell_Name}
</option>
))}
</select>
<h2>From</h2>
<input
type="date"
value={startDate}
onChange={(e) => {
handleDate(e);
}}
name="startDate"
/>
<h2>To</h2>
<input
type="date"
value={endDate}
onChange={(e) => {
handleEndDate(e);
}}
name="endDate"
/>
</div>
<div>
<table>
<thead>
<tr>
<th>E_NodeB</th>
<th>Date</th>
<th>Cell_Name</th>
<th>E_RAB_Setup_Success_Rate</th>
<th>Data_Traffic_DL</th>
<th>Data_Traffic_UL</th>
<th>UL_Throughput</th>
</tr>
</thead>
{selectedSite.map((site, index) => (
<tbody key={index}>
<td>{site.eNodeB_Name}</td>
<td>{site.Cell_Name}</td>
<td>{site.Traffice_Date}</td>
<td>{site.E_RAB_Setup_Success_Rate}</td>
<td>{site.Data_Traffic_DL}</td>
<td>{site.Data_Traffic_UL}</td>
<td>{site.G_UL_Throughput_IK}</td>
</tbody>
))}
</table>
<Line
data={state}
options={{
title: {
display: true,
text: "Plot of E_RAB_Setup_Success_Rate",
fontSize: 20,
},
legend: {
display: true,
position: "right",
},
}}
/>
</div>
</div>
);
};
export default SelectSingle;
`
Backend code
const express = require("express");
const cors = require("cors");
const mysql = require("mysql2");
const app = express();
const connection = mysql.createConnection({
host: "localhost",
user: "a",
password: "123",
database: "aa",
});
connection.connect((err) => {
if (err) throw err;
console.log("Connected to MySQL Server!");
});
app.use(cors());
app.get("/", function (req, res) {
connection.query("SELECT * FROM africell_data LIMIT 10", (err, rows) => {
if (err) throw err;
res.json(rows);
});
});
app.get("/sites", function (req, res) {
connection.query(
`SELECT eNodeB_Name,Cell_Name,Traffice_Date,E_RAB_Setup_Success_Rate,Data_Traffic_DL,Data_Traffic_UL,G_UL_Throughput_IK FROM africell_data`,
(err, rows) => {
if (err) throw err;
res.json(rows);
}`enter code here`
);
});
app.listen(8080, (req, res) => {
console.log(`The app is connected on port 8080`);
});
enter image description here
It appears in your handleDate and handleEndDate functions, you're filtering only for sites which have the specified date (site.Traffice_Date === getDate(e)), which would explain why you're only seeing one date. Try updating the code in your filter block to look for all sites with date above or below your start and end dates, as desired.
I have a modal with a React-Hook-Form that send data to my API and saves it in a MySql database, but when i click on the button, only 4 columns are filled('id', createdAt, updatedAt and user_id), and I have more 3 columns('title', 'description', 'photo').
export default function FeedModal() {
const [form, setForm] = useState([]);
const { register, handleSubmit, setValue } = useForm();
const [isModalVisible, setModalVisible] = useState(false);
useEffect(() => {
register({ title: 'title' });
register({ description: 'description' })
}, [register]);
const onSubmit = async ({ title, description, photo }) => {
const data = { title, description, photo };
await api.post('/posts/1/create')
.then(response => setForm(response(data)))
.then(JSON.stringify(form))
.catch(console.error());
return () => handleSubmit(onSubmit);
}
const toogleModal = () => {
setModalVisible(!isModalVisible);
}
My form:
<View style={styles.Card}>
<View style={styles.pubCard}>
<Text style={styles.intro}>Criar publicação</Text>
<TextInput
value={form.title}
name={'title'}
ref={register({ required: true })}
onChangeText={text => setValue("title", text, { shouldValidate: true })}
multiline={true}
style={styles.titleInput}
placeholder="Titulo">
</TextInput>
</View>
<View style={styles.btnView}>
<TouchableOpacity style={styles.upload} title="Selecionar Foto" >
<Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular', textAlign: 'center' }}>Selecionar Foto</Text>
</TouchableOpacity>
</View>
<KeyboardAvoidingView style={styles.descView}>
<TextInput
value={form.description}
name={"description"}
ref={register({ required: true })}
onChangeText={text => setValue("description", text)}
multiline={true}
style={styles.descInput}
placeholder="Nos descreva com detalhes sobre o caso do seu Pet"></TextInput>
</KeyboardAvoidingView>
<View style={styles.buttons}>
<TouchableOpacity onPress={toogleModal} style={styles.ButtonClose}><Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular' }}>Fechar</Text></TouchableOpacity>
<TouchableOpacity onPress={handleSubmit(onSubmit)} style={styles.ButtonClose}><Text style={{ color: 'white', fontFamily: 'Montserrat_400Regular' }}> Criar</Text></TouchableOpacity>
</View>
</View>
perhaps useFieldArray will be the better usage here since you are talking about the insert.
https://react-hook-form.com/api#useFieldArray
you can then use the insert action. eg:
import React from "react";
import { useForm, useFieldArray } from "react-hook-form";
function App() {
const { register, control, handleSubmit, reset, trigger, setError } = useForm({
// defaultValues: {}; you can populate the fields by this attribute
});
const { fields, append, prepend, remove, swap, move, insert } = useFieldArray({
control,
name: "test"
});
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
<ul>
{fields.map((item, index) => (
<li key={item.id}>
<input
name={`test[${index}].firstName`}
ref={register()}
defaultValue={item.firstName} // make sure to set up defaultValue
/>
<Controller
as={<input />}
name={`test[${index}].lastName`}
control={control}
defaultValue={item.lastName} // make sure to set up defaultValue
/>
<button type="button" onClick={() => remove(index)}>Delete</button>
</li>
))}
</ul>
<button
type="button"
onClick={() => insert(1, { firstName: "appendBill", lastName: "appendLuo" })}
>
append
</button>
<input type="submit" />
</form>
);
}
I'm following the React Native documentation for fetching JSON from an API (https://reactnative.dev/docs/network). I'm new to react and wanting to fetch a wordpress list of posts through its API, but the example they use is very simple and structured differently to how the object is returned from WP.
The problem I'm having is that it is returning the JSON, but I'm unsure how to reference each item I want to display in my flatlist. The line of problem is;
.then((json) => setData(json.movies))
For this WP returned JSON, there is no movies (obviously), in the absence of a referable point what would I specify instead?
My code;
import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
export default App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://public-api.wordpress.com/wp/v2/sites/derbyfutsal.com/posts')
.then((response) => response.json())
.then((json) => setData(json.movies))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Text>{item.title}, {item.excerpt}</Text>
)}
/>
)}
</View>
);
};
You dont have to specify anything, you can directly set the response to the state value and use it in the flatlist.
I've updated the code to display the id instead of title as its an object. You can change it anyway you want and use it.
const App = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://public-api.wordpress.com/wp/v2/sites/derbyfutsal.com/posts')
.then((response) => response.json())
.then((json) => {
setData(json)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<Text>{item.id}</Text>
)}
/>
)}
</View>
);
};
am trying to delete a row based on product code entered, i have 2 functions, one is for search and another is for delete..
Search Function
const handleName = e => {
const idAddProducts = e.target.value;
e.preventDefault();
pnName({ ...poName, idaddproducts: idAddProducts });
handleTable(idAddProducts);
// handleSubmit(idAddProducts);
console.log(poName);
};
async function handleTable(idAddProducts) {
const id = poName.idaddproducts;
const res = await fetch(
"http://localhost:4000/productslist/" + idAddProducts
);
const data = await res.json();
pnName(data.data);
console.log(data.data);
}
useEffect(() => {
handleTable();
}, []);
Another one is Delete Function
const handleN = e => {
const idAddProducts = e.target.value;
e.preventDefault();
pnName({ ...poName, idaddproducts: idAddProducts });
handleSubmit(idAddProducts);
console.log(poName);
};
async function handleSubmit(idAddProducts) {
const res = await fetch(
"http://localhost:4000/productslist/delete/" + idAddProducts
);
const data = await res.json();
pnName(data.data);
console.log(data.data);
}
useEffect(() => {
handleSubmit();
}, []);
Here is the Rendering Part where i map the searched result
<TableBody>
{poName && poName.length ? (
poName.map(row => (
<TableRow key={row.idaddproducts}>
<TableCell component="th" scope="row">
{row.idaddproducts}
</TableCell>
<TableCell component="th" scope="row">
{row.productName}
</TableCell>
<TableCell align="right">{row.productId}</TableCell>
<TableCell align="right">{row.productBrand}</TableCell>
<TableCell align="right">{row.productQuantity}</TableCell>
<TableCell align="right">{row.productPrice}</TableCell>
<TableCell align="right">{row.productType}</TableCell>
</TableRow>
))
) : (
<span>Not Found</span>
)}
</TableBody>
</Table>
</TableContainer>
<div style={{ paddingBlockEnd: "0px" }}>
<Fab color="secondary" aria-label="edit" onClick={handleN}>
<EditIcon />
</Fab>
</div>
So when i add the handleSubmit function directly in to handleName, its getting deleted as i type, so i had to create seperate function as HandleN and call handle submit so that when i click button it should execute,
instead sql throws as Error:
ER_TRUNCATED_WRONG_VALUE: Truncated incorrect DOUBLE value:
'undefined'
or
Error: ER_TRUNCATED_WRONG_VALUE: Truncated incorrect DOUBLE value:
'[object]%20[object]'
Any help ?
export default function DeleteProductsForm() {
const initialState = {
idaddproducts: "",
productName: "",
productId: "",
productBrand: "",
productQuantity: "",
productPrice: "",
productType: ""
};
const [values, setValues] = React.useState(initialState);
const handleName = e => {
const idAddProducts = e.target.value;
console.log(idAddProducts);
e.preventDefault();
setValues({ ...values, [e.target.name]: idAddProducts });
handleList1(idAddProducts);
console.log(values);
};
const handleN = e => {
const idAddProducts = values.idaddproducts;
console.log(idAddProducts);
e.preventDefault();
setValues({ ...values, [e.target.name]: idAddProducts });
handleList(idAddProducts);
console.log(values);
};
async function handleList1(idAddProducts) {
const res = await fetch(
"http://localhost:4000/productslist/" + idAddProducts
);
const data = await res.json();
setValues(data.data);
console.log(data.data);
}
useEffect(() => {
handleList1();
}, []);
async function handleList(idAddProducts) {
const res = await fetch(
"http://localhost:4000/productslist/delete/" + idAddProducts
);
const data = await res.json();
setValues(data.data);
console.log(data.data);
}
useEffect(() => {
handleList();
}, []);
const classes = useStyles();
return (
<form className={classes.root} noValidate autoComplete="off" align="center">
<div className={classes.formGroup}>
<FormControl>
<Input
type="search"
label="Product ID"
variant="outlined"
size="small"
placeholder="Enter Product Code"
value={values.idaddproducts}
name="idaddproducts"
onChange={e => handleName(e)}
/>
</FormControl>
<Button onClick={e => handleN(e)}>Click</Button>
{values && values.length ? (
values.map(row => <h5 key={row.idaddproducts}>{row.productName}</h5>)
) : (
<h5>Not Found</h5>
)}
</div>
</form>
);
}
if i delete handleList1 function it works fine.. but it wont display data