I'm new to React Native, sorry for mistakes on the code. I use React Native and SQLite (all expo).
My problem is that the "useState" does not save the data when entering the application, I have to update the app (Ctrl s in Visual Studio Code) manually for it to save the data. I do not know why this is happening, can anyone tell me what the problem?
- The console shows "array []" initially and after updating the data appears inside the array
edit my code :)
console (first) ->
use effect 0 ------> Array []
use effect 1 ------> null
ENCONTRADO de tb_user o ID_user, username, nome_empresa ---> SORAIA
ENCONTRADO de tb_veic_user o ID_veic_uso onde kmf=null
console (second) ->
use effect 0 ------> Array [
Object {
"ID_veic_uso": 1,
},
]
use effect 1 ------> null
ENCONTRADO de tb_user o ID_user, username, nome_empresa ---> SORAIA
ENCONTRADO de tb_veic_user o ID_veic_uso onde kmf=null
console (third) ->
use effect 0 ------> Array [
Object {
"ID_veic_uso": 1,
},
]
use effect 1 ------> 1
ENCONTRADO de tb_user o ID_user, username, nome_empresa ---> SORAIA
ENCONTRADO de tb_veic_user o ID_veic_uso onde kmf=null
const [dados, setDados] = useState([]);
const [IDVeic, setIDVeic] = useState(null);
const findByUserna = (userna) => {
return new Promise((resolve, reject) => {
db.transaction((tx) => {
//comando SQL modificável
tx.executeSql(
"SELECT ID_user, username, nome_empresa FROM tb_user WHERE username = ?;",
[route.params.paramKey],
//-----------------------
(_, { rows }) => {
if (rows.length > 0) {
resolve(rows._array),
console.log('ENCONTRADO de tb_user o ID_user, username, nome_empresa ---> ',route.params.paramKey);
}else {
reject("Obj not found: id=" userna),
console.log('NAO ENCONTRADO de tb_user o ID_user, username, nome_empresa');
} // nenhum registro encontrado
},
(_, error) => reject(error) // erro interno em tx.executeSql
);
});
});
};
const findByV = (cont) => {
return new Promise((resolve, reject) => {
db.transaction((tx) => {
tx.executeSql(
"SELECT ID_veic_uso FROM tb_veic_user WHERE username LIKE ? AND km_final IS NULL",
[route.params.paramKey],
//-----------------------
(_, { rows }) => {
if (rows.length > 0) {
resolve(rows._array),
console.log('ENCONTRADO de tb_veic_user o ID_veic_uso onde kmf=null');
}else {
reject("Obj not found: v=" cont),
console.log('NAO ENCONTRADO de tb_veic_user o ID_veic_uso onde kmf=null');
}
} // erro interno em tx.executeSql
);
});
});
};
useEffect(() => {
findByUserna( route.params.paramKey )
.then(
findByV(route.params.paramKey)
.then(
d => {
setDados(d)
}
)
)
.then(console.log('use effect 0 ------>',dados))
.then(
dados.map(item =>
setIDVeic(item.ID_veic_uso)
),
)
.then(console.log('use effect 1 ------>',IDVeic))
},[])
Every time i save my file in vs code 1 useState works
CodePudding user response:
The setter
function of a state
is asynchronous in react native. Thus, if you console.log
the state object directly after setting it in the useEffect
, it won't show the updated state.
However, a state
change will trigger a rerender of your component, and it is guaranteed by the framework that the state
will contain the updated value in the next render cycle.
We can verify that by putting the console.log
outside of the useEffect
.
const [dados, setDados] = useState([]);
useEffect(() => {
findByV(route.params.paramKey)
.then(
d => {
setDados(d),
},
)
},[])
console.log('data', dados)
We will notice two log messages. The first one is an empty array, which is the initial value of the state dados
. The useEffect
has an empty dependency array, thus it will be triggered exactly once if the component mounts. If we set a new state using setDados
, it will trigger a new render cylce and the whole component renders again. This time the useEffect
will not be triggered, but the state
contains the new value.
CodePudding user response:
The problem is that I use the const 'data' at the end of my code in a condition (if 'data' is not null, it renders certain component). And this it doesn't read the 'IDVeic'
return (
<Image
style={fundoVeic.imageLogo}
source={require('../../imagens/aaa.png')}
/>
{IDVeic === null ?
<View>...</View>
:
<View>...</View
}