2
I’m trying to do the following procedure at React Native, with the Expo:
I have some data stored in Asyncstorage of the device. The code below returns me the following result:
CODE
AsyncStorage.getAllKeys((err, keys) => {
AsyncStorage.multiGet(keys, (err, stores) => {
console.log(stores);
});
});
RESULT
Array [
Array [
"webservice_qng7ike7r",
"{\"idWebservice\":\"qng7ike7r\",\"enderecoWebservice\":\"Endereço 2\",\"nomeWebservice\":\"Nome 2\"}",
],
Array [
"webservice_t572op73v",
"{\"idWebservice\":\"t572op73v\",\"enderecoWebservice\":\"Endereço 1\",\"nomeWebservice\":\"Nome 1\"}",
],
Array [
"webservice_u6alr9qo8",
"{\"idWebservice\":\"u6alr9qo8\",\"enderecoWebservice\":\"Endereço 3\",\"nomeWebservice\":\"Nome 3\"}",
],
]
In order to assemble a suitable object, containing only the necessary information from the Webservice, I am doing the following procedure:
AsyncStorage.getAllKeys((err, keys) => {
AsyncStorage.multiGet(keys, (err, stores) => {
for (let i = 0; i < stores.length; i++) {
const webserviceCorrente = stores[i];
const objWebservice = JSON.parse(webserviceCorrente[1]);
const data = {
idWebservice: objWebservice.idWebservice,
nomeWebservice: objWebservice.nomeWebservice,
enderecoWebservice: objWebservice.enderecoWebservice,
}
console.log(data);
}
});
});
So far, so good. It returns me the object this way below:
Object {
"enderecoWebservice": "Endereço 1",
"idWebservice": "t572op73v",
"nomeWebservice": "Nome 1",
}
What I want, is to assemble an array where each index of it is an object containing this data, of the 3 registered addresses.
I’m trying to do it this way, but without success:
Declaring the State of the array
const [arrWebservices, setArrWebservices] = useState([]);
Mounting the object array (unsuccessfully)
AsyncStorage.getAllKeys((err, keys) => {
AsyncStorage.multiGet(keys, (err, stores) => {
for (let i = 0; i < stores.length; i++) {
const webserviceCorrente = stores[i];
const objWebservice = JSON.parse(webserviceCorrente[1]);
const data = {
idWebservice: objWebservice.idWebservice,
nomeWebservice: objWebservice.nomeWebservice,
enderecoWebservice: objWebservice.enderecoWebservice,
}
setArrWebservices({ ...arrWebservices, data });
}
});
});
Can someone help me, please? I searched through the internet but could not find a solution.
If you need any more information, let me know.
Thanks in advance!
Besides, it’s a bad idea to run
setState
within a synchronous loop, the type must be Array , not Object. That is, these{ ... }
should be[...]
?– Sergio