Why doesn't the called API data appear in the native picker? ,
Previously there was an ActivityIndicator and it was only loading, then I deleted the ActivityIndicator but the API data didn't appear, but the console.log data was called, why?
const [data, setdata] = useState();
useEffect(() => {
const callApi = async () => {
await getData();
};
callApi();
}, []);
,,,,
,,,,
return (
<View style={styles.container}>
<Text style={styles.text}>Pilih Data</Text>
<View style={styles.picker}>
<Picker
selectedValue={data}
onValueChange={itemValue => setdata(itemValue)}>
{data &&
data?.map((item, key) => {
<Picker.Item
label={'${item.bencana}'}
value={'${item.ID }'}
key={key}
/>;
})}
</Picker>
</View>
)
Related
That's my code which was fixed in the previous question, and still the error occurs, the data is not showing just showing loading, how to fix that ?
const Sub_Map = () => {
const [hasLoaded, setHasLoaded] = useState(false);
const [data, setdata] = useState();
useEffect(() => {
const callApi = async () => {
await getData();
setHasLoaded(true);
};
callApi();
}, []);
const getData = () => {
fetch('http:// . . . ./aplikasi/restapi.php?op=getJenis')
.then(response => response.json())
.then(json => {
// console.log(json);
setdata(json);
// console.log(data);
});
};
Maybe there is another correction for the return part?
return (
<View style={styles.container}>
<Text style={styles.text}>Pilih Data</Text>
<View style={styles.picker}>
{hasLoaded ? (
<ActivityIndicator />
) : (
<Picker
selectedValue={data}
onValueChange={itemValue => setdata(itemValue)}>
{data &&
data?.map((item, key) => {
<Picker.Item
label={'${item.bencana}'}
value={'${item.ID }'}
key={key}
/>;
})}
</Picker>
)}
</View>
);
};
and this is for API , there may be a correction
function getJenis()
{
global $conn;
global $json;
global $obj;
$sql = mysqli_query($conn, "SELECT * FROM bencana_detail ORDER BY bencana ASC");
while ($row = mysqli_fetch_array($sql)) {
$hasil[] = array(
'ID' => $row['id_bencana_detail'],
'bencana' => $row['bencana']
);
}
echo json_encode($hasil);
}
Try this it should work
{data.length <= 0 ? (
<ActivityIndicator />
) : (
<Picker
selectedValue={data}
onValueChange={itemValue => setdata(itemValue)}>
{data &&
data?.map((item, key) => {
<Picker.Item
label={'${item.bencana}'}
value={'${item.ID }'}
key={key}
/>;
})}
</Picker>
)}
I'm new to drawing a graph with react-native. The problem is, I can read the data sent with Ble as a value on the screen, but I'm having trouble making real-time graphs. There must be a mistake somewhere. I tried many different methods.
The code below is my screen code.
const disconnectDevice = useCallback(async () => {
navigation.goBack();
const isDeviceConnected = await device.isConnected();
if (isDeviceConnected) {
await device.cancelConnection();
navigation.navigate('Home');
}
}, [device, navigation]);
useEffect(() => {
const getDeviceInformations = async () => {
// connect to the device
const connectedDevice = await device.connect();
setIsConnected(true);
// discover all device services and characteristics
const allServicesAndCharacteristics = await connectedDevice.discoverAllServicesAndCharacteristics();
// get the services only
const discoveredServices = await allServicesAndCharacteristics.services();
setServices(discoveredServices);
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Permission Localisation Bluetooth',
message: 'Requirement for Bluetooth',
buttonNeutral: 'Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
};
getDeviceInformations();
device.onDisconnected(() => {
navigation.navigate('Home');
});
// give a callback to the useEffect to disconnect the device when we will leave the device screen
return () => {
disconnectDevice();
navigation.navigate('Home');
};
}, [device, disconnectDevice, navigation]);
return (
<ScrollView contentContainerStyle={styles.container}>
<TouchableOpacity style={styles.button} onPress={disconnectDevice}>
<Text style={{fontFamily:"SairaExtraCondensed-Thin",textAlign:"center",fontSize:15,color:"white"}}>Antrenmanı Sonlandır</Text>
</TouchableOpacity>
<View>
<View style={styles.header} >
<Text>{`Name : ${device.name}`}</Text>
<Text>{`Is connected : ${isConnected}`}</Text>
</View>
<View>
<>
{services &&
services.map((service) => {
return(
<>
<ServiceCard service={service} />
<LineChart
style={{ height: 200 }}
gridMin={0}
gridMax={300}
data={[service]}
svg={{ stroke: 'rgb(134, 65, 244)' }}
contentInset={{ top: 20, bottom: 20 }}>
</LineChart></>
)
})}
</>
</View>
</View>
<View>
</View>
</ScrollView>
);
};
The service component, where the values were decoded last, is as follows;
type ServiceCardProps = {
service: Service;
};
const ServiceCard = ({ service }: ServiceCardProps) => {
const [descriptors, setDescriptors] = useState<Descriptor[]>([]);
const [characteristics, setCharacteristics] = useState<Characteristic[]>([]);
const [areCharacteristicsVisible, setAreCharacteristicsVisible] = useState(
false,
);
useEffect(() => {
const getCharacteristics = async () => {
const newCharacteristics = await service.characteristics();
setCharacteristics(newCharacteristics);
newCharacteristics.forEach(async (characteristic) => {
const newDescriptors = await characteristic.descriptors();
setDescriptors((prev) => [...new Set([...prev, ...newDescriptors])]);
});
};
getCharacteristics();
}, [service]);
return (
<View style={styles.container}>
<TouchableOpacity
onPress={() => {
setAreCharacteristicsVisible((prev) => !prev);
}}>
<Text>{`UUID : ${service.uuid}`}</Text>
</TouchableOpacity>
{areCharacteristicsVisible &&
characteristics &&
characteristics.map((char) => (
<CharacteristicCard key={char.id} char={char} />
))}
{descriptors &&
descriptors.map((descriptor) => (
<DescriptorCard key={descriptor.id} descriptor={descriptor} />
))}
</View>
);
};
Data is being decoded with Ble. Then it is displayed as a value on the screen via the latest service map. I want to see the graph on the screen in real time like in this code. What error could be below?
Nothing appears on the screen. I only see values.
Thanks
So I have a screen in react-native in my android app for reporting faulty equipment on my university and I have a wierd issue with my accordion menu. I use it as a list of options for the type of broken equipment that I store and then send to the database. After testing I found out the acordion menu doesnt close even if I edit the function to change the state that should track if the menu shoudl be open or not. Anybody any ideas?
const [typeOfEquip, setTypeOfEquip] = useState('');
const [expanded, setExpanded] = React.useState(true);
const chooseType= (typ) =>{
setTypeOfEquip(typ);
handlePress();
}
const handlePress = () => setExpanded(!expanded);
<List.AccordionGroup>
<List.Accordion
title="Type of equipment"
expanded={expanded}
onPress={handlePress}
id="1">
<List.Item
title="Svetla"
onPress={() => {
chooseType('Svetla');
}}
/>
<List.Item
title="Stoličky"
onPress={() => {
chooseType('Stoličky');
}}
/>
</List.Accordion>
I guess you are having this issue because of default behaviour. In onPress of
List.Accordion you are calling handlePress() and children of List.Accordion which is List.Item calling chooseType function. chooseType also calls handlePress function inside. Try adding e.preventDefault() to functions
const [typeOfEquip, setTypeOfEquip] = useState('');
const [expanded, setExpanded] = React.useState(true);
const chooseType= (e, typ) =>{
e.preventDefault();
setTypeOfEquip(typ);
handlePress();
}
const handlePress = (e) => {
e.preventDefault();
setExpanded(!expanded);
}
<List.AccordionGroup>
<List.Accordion
title="Type of equipment"
expanded={expanded}
onPress={handlePress}
id="1">
<List.Item
title="Svetla"
onPress={(e) => {
chooseType(e, 'Svetla');
}}
/>
<List.Item
title="Stoličky"
onPress={(e) => {
chooseType(e, 'Stoličky');
}}
/>
</List.Accordion>
I'm working with React-native-sqlite-storage (React native CLI). And the thing is that getmysqliData dosn't excute tx.executeSql function when I query the sqlite. And I don't know why.
the whole code is this:
https://gist.github.com/BravenxX/247f97c0576881616c24d197cdd137f6
About the code:
state: data: [--DATA--] .... is temporaly, this should must be replaced with the sqlite elements in getMysqliData function.
the are 2 arrays because I use them as a real time filter (it has nothing to do with sqlite btw)
const db = SQLite.openDatabase({ name: "geslub", createFromLocation: "~databases/geslub.db" });
class TablaActProgramadas extends Component{
constructor(props){
super(props);
this.state={
value: '',
isLoading: true,
data:[
{'Faena': 'aDDLB', 'Planta': 'taller Titan', 'Linea': 'Kmotasú', 'Equipo': 'Caex', 'Componente': 'N/A'}
],
arrayholder: [
{'Faena': 'aDDLB', 'Planta': 'taller Titan', 'Linea': 'Kmotasú', 'Equipo': 'Caex', 'Componente': 'N/A'}
],
};
};
async componentDidMount(){
await this.getMysqliData();
console.log('TERMINO: ComponenntDIDMOUNT')
}
getMysqliData(){
const sql = 'SELECT * FROM actividades_programadas';
db.transaction((tx) => {
//TX.EXECUTESQL is not executed!!
tx.executeSql(sql, [], (tx, results) => {
if(results.rows._array.length > 0){
this.setState({
data: results.rows_array,
arrayholder: results.rows_array,
isLoading: false
})
}else{
Alert.alert('ERROR en la carga de datos')
}
});
});
}
componentWillUnmount() {
this.closeDatabase();
}
closeDatabase = () => {
if (db) {
db.close();
} else {
console.log("Database no estaba abierta");
}
}
renderHeader = () => {
return (
<SearchBar
placeholder="Filtro general..."
lightTheme
round
onChangeText={text => this.searchFilterFunction(text)}
autoCorrect={false}
value={this.state.value}
/>
);
};
searchFilterFunction = text => {
this.setState({
value: text,
});
const newData = this.state.arrayholder.filter(item => {
const itemData = `${item.Faena.toUpperCase()} ${item.Planta.toUpperCase()} ${item.Linea.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({
data: newData,
});
};
render(){
if(this.state.isLoading)
return (
<View style={stylesLoading.container}>
<View>
<ActivityIndicator size="large" color="lightblue"/>
</View>
<View>
<Text style={stylesLoading.texto}>
Descargando datos...
</Text>
</View>
</View>
)
else
return(
<FlatList
data={this.state.data}
showsVerticalScrollIndicator={false}
keyExtractor={(item, index) => index.toString()}
renderItem={({item}) =>(
<TouchableOpacity onPress={() => this.props.navigation.navigate('RealizarActProgramadas', {
faena: `${item.Faena}`, //ENVIAR ID DE LA ACTIVIDAD A REALIZAR
otherParam: 'anything you want here',
})}>
<ListItem
title={`Faena: ${item.Faena}`}
subtitle={`Planta: ${item.Planta}\nLinea: ${item.Linea}`}
/>
</TouchableOpacity>
)}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader()}
/>
);
}
}
I have the same issue. This ocurred because you openDasaBase is create a new database file and not use your imported file.
In my case for android I needed to put de sqlite file in android/src/main/assets/www/test.db
And use this config to open:
var db = openDatabase({name: 'test.db', createFromLocation: 1}, () => {
console.log("Database OPENED");
}, (err) => {
console.log("SQL Error: " + err);
});
This is better described in docs https://github.com/andpor/react-native-sqlite-storage#importing-a-pre-populated-database
I'm making a list view were I will view a list of some data from my database. But after running the program all I got is white background screen. Does anyone knows the solution?
screen shot
Here is my code
export default class Pasta extends Component {
constructor() {
super()
this.state = {
dataSource: []
}
}
renderItem = ({ item }) => {
return (
<View style = {{flex: 1, flexDirection: 'row'}}>
<View style = {{flex: 1, justifyContent: 'center'}}>
<Text>
{item.menu_desc}
</Text>
<Text>
{item.menu_price}
</Text>
</View>
</View>
)
}
componentDidMount() {
const url = 'http://192.***.***.***:9090/menu'
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson.menu
})
})
}
render() {
return (
<View style = { styles.container }>
<FlatList
data = { this.state.dataSource }
renderItem = {this.renderItem}
/>
</View>
);
}
}
Add extraData prop to your FlatList to cause a re-render
keyExtractor = (item, index) => item.id; // note: id is the unique key for each item
render() {
return (
<FlatList
data = {this.state.dataSource}
renderItem = {this.renderItem}
extraData={this.state}
keyExtractor={this.keyExtractor}
/>
);
}
Also log and verify your data is present. I suggest referring to FlatList docs for more props like keyExtractor etc.