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
I call myGET_REQUESTaction in a screen, my Sagamakes the request and triggers my GET_SUCCESS action but, my screen doesn't re-render on it's own, only when I update the component's state, a re-render is triggered and the new props reflecting the store show up.
so... my store apparently works fine, in Reactotron the store is filled, as you can see below:
https://user-images.githubusercontent.com/27635248/54751638-52671b80-4bba-11e9-9f9b-b7eee7f3deba.png
My user Reducer:
export const Types = {
GET_SUCCESS: 'user/GET_SUCCESS',
GET_REQUEST: 'user/GET_REQUEST',
GET_FAILURE: 'user/GET_FAILURE',
UPDATE_USER: 'user/UPDATE_USER',
REHYDRATE_SUCCESS: 'user/REHYDRATE_SUCCESS',
REHYDRATE_FAILURE: 'user/REHYDRATE_FAILURE',
}
const INITIAL_STATE = {
data: {},
status: {
loading: false,
error: null,
}
}
export default function user(state = INITIAL_STATE, action) {
switch (action.type) {
case Types.GET_SUCCESS: {
return {
...state,
data: action.payload.user,
status: {
...state.status,
loading: false,
error: null
}
}
}
case Types.GET_REQUEST: {
return {
...state,
status: {
error: null,
loading: true
}
}
}
case Types.GET_FAILURE: {
if (Object.keys(state.data).length) {
action.payload.isStateEmpty = false
return {
...state,
status: {
...state.status,
loading: false
}
}
} else {
return {
...state,
status: {
...state.status,
loading: false
}
}
}
}
case Types.REHYDRATE_SUCCESS: {
return {
...state,
data: action.payload.user,
status: {
error: null,
loading: false
}
}
}
case Types.REHYDRATE_FAILURE: {
return {
...state,
status: {
loading: false,
error: action.payload.error
}
}
}
case Types.UPDATE_USER: {
return {
...state,
data: {
...state.data,
...action.payload.data
}
}
}
default: {
return state
}
}
}
export const Creators = {
getUserSuccess: user => ({
type: Types.GET_SUCCESS,
payload: {
user,
},
}),
getUserRequest: () => ({
type: Types.GET_REQUEST,
payload: {}
}),
getUserFailure: error => ({
type: Types.GET_FAILURE,
payload: {
error,
isStateEmpty: true
}
}),
rehydrateUserSuccess: user => ({
type: Types.REHYDRATE_SUCCESS,
payload: {
user
}
}),
rehydrateUserFailure: error => ({
type: Types.REHYDRATE_FAILURE,
payload: {
error
}
}),
updateUser: data => ({
type: Types.UPDATE_USER,
payload: {
data
}
}),
}
My user saga:
import { Types } from '../ducks/user'
import { call, put, takeLatest } from 'redux-saga/effects'
import { Creators as UserActions } from '../ducks/user'
import API from 'utils/api'
import DAO from '../../utils/dao';
function formatUsuarioToDbKeys(usuario, pk_pessoa) {
return {
pk_user: usuario.id,
fk_pessoa: pk_pessoa,
username_usu: usuario.username,
email_usu: usuario.email,
first_name_usu: usuario.first_name,
las_name_usu: usuario.last_name,
ativo_usu: usuario.ativo,
}
}
function formatPessoaToDbKeys(pessoa) {
return {
pk_pessoa: pessoa.pessoa_id,
fk_funcao: pessoa.funcao_id,
nome_pes: pessoa.nome,
codigo_erp_pes: pessoa.codigo_erp,
ativo_pes: pessoa.ativa,
}
}
function formatFuncaoToDbKeys(funcao) {
return {
pk_funcao: funcao.id,
nome_fun: funcao.nome,
}
}
function formatEquipeToDbKeys(equipe) {
return {
pk_equipe: equipe.id,
nome_equ: equipe.nome,
ativo_equ: equipe.ativo,
}
}
function* getUser() {
try {
const dados = yield call(API.getInstance().getRequest, '/initializer/?tipo=1')
const funcao = yield call(formatFuncaoToDbKeys, dados.funcao)
const pessoa = yield call(formatPessoaToDbKeys, dados.pessoa)
const usuario = yield call(formatUsuarioToDbKeys, ...[dados.usuario, dados.pessoa.pessoa_id])
const equipe = yield call(formatEquipeToDbKeys, dados.equipe)
yield put(UserActions.getUserSuccess({ usuario, pessoa, funcao, equipe }))
yield call(DAO.getInstance().createFuncao, funcao)
yield call(DAO.getInstance().createPessoa, pessoa)
yield call(DAO.getInstance().createUsuario, usuario)
yield call(DAO.getInstance().createEquipe, equipe)
} catch (error) {
yield put(UserActions.getUserFailure('Ocorreu um erro ao buscar dados do usuário.'))
yield call(console.warn, error.message)
}
}
function* rehydrateUser(action) {
if (action) {
try {
const user = yield call(DAO.getInstance().getUsuario)
yield put(UserActions.rehydrateUserSuccess(user))
} catch (error) {
yield put(UserActions.rehydrateUserFailure('Ocorreu um erro ao buscar dados do usuário.'))
yield call(console.warn, error.message)
}
}
}
export default sagas = [
takeLatest(Types.GET_REQUEST, getUser),
takeLatest(Types.GET_FAILURE, rehydrateUser)
]
and, finally this is my component:
class Dashboard extends Component {
...state and others methods
componentDidMount() {
this.props.getUserRequest()
this.props.getConstructionsRequest()
}
render() {
const spin = this.state.spin_value.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg']
})
return (
<View style={{ flex: 1 }}>
<StatusBar
hidden={false}
backgroundColor={colors.blueDarker} />
<ScrollView
ref={'refScrollView'}
stickyHeaderIndices={[2]}
style={styles.container}>
<ImageBackground
source={require('imgs/capa_dashboard.png')}
blurRadius={4}
style={styles.imageBackground}>
<View style={styles.headerContainer}>
<Text style={styles.textVersion}>{require('../../../package.json').version}</Text>
<Animated.View style={{ transform: [{ rotate: spin }] }}>
<TouchableOpacity
onPress={() => {
this._spinIcon()
this._handleRefresh()
}}>
<MaterialIcons
name={'refresh'}
size={35}
style={styles.refreshIcon}
color={'white'} />
</TouchableOpacity>
</Animated.View>
</View>
<View style={styles.headerButtonsContainer}>
<HeaderLeft
navigation={this.props.navigation} />
<Image
style={styles.image}
source={require('imgs/logo_header.png')} />
<HeaderRight />
</View>
<View style={{ flex: 1, justifyContent: 'center' }}>
{!this.props.user.status.loading && !!Object.keys(this.props.user.data).length
? <View>
<Text style={[styles.textNome, { textAlign: 'center' }]}>{this.props.user.data.pessoa.nome_pes}</Text>
<Text style={styles.textAuxiliar}>{this.props.user.data.funcao.pk_funcao == 1 ? this.props.user.data.equipe.nome_equ : 'Engenheiro(a)'}</Text>
</View>
: <ActivityIndicator style={{ alignSelf: 'center' }} size={'large'} color={colors.blue} />
}
</View>
</ImageBackground>
<ActionsButtons
stylesButton1={{ borderBottomColor: this.state.button_obras_selected ? 'white' : colors.transparent }}
stylesText1={{ color: this.state.button_obras_selected ? 'white' : 'lightgrey' }}
numberButton1={this.props.count_obras}
callbackButton1={async () => this.setState({ button_obras_selected: true })}
stylesButton2={{ borderBottomColor: !this.state.button_obras_selected ? 'white' : colors.transparent }}
stylesText2={{ color: !this.state.button_obras_selected ? 'white' : 'lightgrey' }}
numberButton2={this.state.count_enviar}
callbackButton2={async () => this.setState({ button_obras_selected: false })}
/>
<View>
{this.state.button_obras_selected
? <View style={styles.containerTextInput} >
<TextInput
onEndEditing={() => this._handleEndSearch()}
onFocus={() => this._handleStartSearch()}
ref={'textInputRef'}
style={styles.textInput}
onChangeText={search_text => this._filterSearch(search_text)}
autoCapitalize="none"
onSubmitEditing={() => this._handleClickSearch()}
underlineColorAndroid='rgba(255,255,255,0.0)'
placeholder={'Buscar obras...'} />
<TouchableOpacity
onPress={() => this._handleClickSearch()}
style={styles.searchImage}>
<MaterialCommunityIcons
name={'magnify'}
size={30}
color={'black'} />
</TouchableOpacity>
</View >
: null}
</View>
<View>
{this.state.button_obras_selected
? !this.props.constructions.status.loading && !!Object.keys(this.props.constructions.data).length
? <View style={{ flex: 1, marginTop: 8 }}>
<FlatList
data={this.props.constructions.data}
removeClippedSubviews={true}
keyExtractor={item => item.pk_obra.toString()}
renderItem={obra =>
<ObraComponent
callback={this._callbackObra}
item={obra.item}
isCurrentObra={nome => this.state.obra_atual == nome}
/>
}
/>
</View>
: <ActivityIndicator style={{ marginTop: 150 }} size={50} color={colors.blueDarker} />
:
<View style={{
flex: 1,
marginTop: 8,
}}>
<FlatList
data={[]}
removeClippedSubviews={true}
keyExtractor={item => item.fk_obra.toString()}
renderItem={acao =>
<AcaoComponent item={acao.item} />
}
/>
</View>
}
</View>
</ScrollView>
</View>
)
}
}
const mapStateToProps = state => ({
user: state.user,
constructions: state.constructions,
count_obras: state.constructions.data.length
})
const mapDispatchToProps = dispatch =>
bindActionCreators({
...UserActions,
...ConstructionsActions.DEEP,
...ConstructionsActions.SHALLOW
}, dispatch)
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard)
As I said before, I call getUserRequest() to fire GET_REQUEST action on componentDidMount() but, when the request is done and my redux store is updated, my screen stays loading like this, even if the loading state in the store is false
https://user-images.githubusercontent.com/27635248/54752551-4e88c880-4bbd-11e9-9164-5fad46db6c13.png
I've used very similar store and saga structures in other projects, but for some reason, in this specific one, I haven't been able to figure it out
When I press one of these buttons, the component updates it's state and this triggers a re-render, then finally the data from my store shows up as props in the censored areas - this was the only way I figured out to re-render stuff with redux(in this project at least), forcing a re-render by updating the components state using this.setState():
https://user-images.githubusercontent.com/27635248/54752771-fef6cc80-4bbd-11e9-9d15-a46acb87f3a4.png
I'm not sure what's wrong with my implementation, i've checked out other similiar issues, none of them seemed to work, if anyone has a suggestion, feel welcome to post them below, thank you in advance.
"axios": "^0.18.0",
"react-native": "~0.55.2",
"react-redux": "^6.0.0",
"reactotron-redux": "^2.1.3",
"reactotron-redux-saga": "^4.0.1",
"redux": "^4.0.1",
"redux-saga": "^1.0.1",
EDIT:
So, as far as my understanding goes, updating redux's store reflectes on new props to the connected components, and React does update them based on a shallow compare. I've experimented a bit, and for some reason, my actions are triggered, sagas run fine, and the store is changing successfuly, but mapStateToProps is not being called after my success action is triggered.
Basically I'm not able to choose if the component should update (using shouldComponentUpdate to compare prevProps and this.props) because the component is not even receiving new props from mapStateToProps.
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.
I can't display json data in listview. I get json data in console.log but not in listview isLoading is always on false.
I dont get any errors .catch(error => console.warn("error")).
Result on screen is first View because this.state.isLoading is false.
Here is a code:
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, ListView, Text, View,Image,TouchableHighlight } from 'react-native';
var productArray = [];
class ListViewDemo extends Component {
constructor(props) {
console.warn("constructor");
super(props);
var dataSource = new ListView.DataSource({rowHasChanged:(r1,r2) => r1.guid != r2.guid});
this.state = {
dataSource: dataSource.cloneWithRows(productArray),
isLoading:true
}
}
componentDidMount() {
console.warn("componentDidMount");
this.getTheData(function(json){
productArray = json;
console.warn(productArray);
this.setState = ({
datasource:this.state.dataSource.cloneWithRows(productArray),
isLoading:false
})
}.bind(this));
console.warn("component -> " + this.state.isLoading);
}
getTheData(callback) {
console.warn("callback");
var url = "https://raw.githubusercontent.com/darkarmyIN/React-Native-DynamicListView/master/appledata.json";
fetch(url)
.then(response => response.json())
.then(json => callback(json))
.catch(error => console.warn("error"));
}
renderRow(rowData, sectionID, rowID) {
console.warn("renderRow");
return (
<TouchableHighlight underlayColor='#dddddd' style={{height:44}}>
<View>
<Text style={{fontSize: 20, color: '#000000'}} numberOfLines={1}>{rowData.display_string}</Text>
<Text style={{fontSize: 20, color: '#000000'}} numberOfLines={1}>test</Text>
<View style={{height: 1, backgroundColor: '#dddddd'}}/>
</View>
</TouchableHighlight>
);
}
render() {
console.warn("render" + this.state.isLoading);
var currentView = (this.state.isLoading) ? <View style={{height: 110, backgroundColor: '#dddddd'}} /> : <ListView dataSource={this.state.dataSource} renderRow={this.renderRow.bind(this)} enableEmptySections={true}/>
return(
<View>
{currentView}
</View>
);
}
}
// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => ListViewDemo);
I see a couple of mistakes here.
In your componentDidMount, you are setting datasource intead of dataSource:
componentDidMount() {
console.warn("componentDidMount");
this.getTheData(function(json){
productArray = json;
console.warn(productArray);
this.setState = ({
//datasource:this.state.dataSource.cloneWithRows(productArray),
dataSource:this.state.dataSource.cloneWithRows(productArray),
isLoading:false
})
}.bind(this));
console.warn("component -> " + this.state.isLoading);
}
That's why you're not being able to render, because dataSource is never populated. It is just a little spelling mistake.
You are probably not getting into the second then in your getTheData method because you are not returning a Promise:
getTheData(callback) {
console.warn("callback");
var url = "https://raw.githubusercontent.com/darkarmyIN/React-Native-DynamicListView/master/appledata.json";
fetch(url)
//.then(response => response.json())
.then(response => return response.json())
.then(json => callback(json))
.catch(error => console.warn("error"));
}
Your are making a mistake with your setState, your are assigning it instead of calling it:
//this.setState = ({
// datasource:this.state.dataSource.cloneWithRows(productArray),
// isLoading:false
//})
this.setState({
dataSource:this.state.dataSource.cloneWithRows(productArray),
isLoading:false
})
Let me know if it works.
You are setting the function setState instead of calling it
this.setState = ({
datasource:this.state.dataSource.cloneWithRows(productArray),
isLoading:false
})
should be
this.setState({
datasource:this.state.dataSource.cloneWithRows(productArray),
isLoading:false
})