-1
I’m trying to access some specific values of an object within an array, from a get method response using Xios.
I’d like to access id
, dateTime
, sensorData
etc of each array object separately, for example: result[0].id
Excerpt from the code:
const ShowSensorsScreen = ({ navigation }) => {
const [ result, setResult ] = useState([]);
const id = navigation.getParam('id');
console.log(result[0].id);
const getResult = async id => {
const response = await searchApi.get(`/sensorData/${id}`);
setResult(response.data);
};
useEffect(() => {
getResult(id);
}, []);
Result sample:
Array []
Array [
Object {
"sensorData01": "100.00000",
"sensorData02": "101.00000",
"sensorData03": "102.00000",
"sensorData04": "103.00000",
"dateTime": "2020-01-06T23:10:56Z",
"id": 1,
"idEvaluation": 1,
},
Object {
"sensorData01": "110.00000",
"sensorData02": "111.00000",
"sensorData03": "112.00000",
"sensorData04": "113.00000",
"dateTime": "2020-01-06T23:11:16Z",
"id": 2,
"idEvaluation": 1,
},
]
This code is a class or function component ?
console.log(result)
gives what ?– Isac
(First I am beginner) Hello I am trying to make all the code in function component without class use; First problem I solved with help, it was an asynchronicity error in setting the result before receiving the answer as I understood. The biggest problem is accessing individual values of array objects, type Undefined is not an Object
– Saga Gemini
You do this using map.
<View>
{result.map(item => <Text>item.id</Text>)}
</View>
Da to render javascript codes in the jsx of the React with {}. If you want you can create a method for this tbm. the first time it renders empty, the second time it renders the list.– Leandro Sena
Thank you @Leandrosena, really using map() I was able to create a new array for each of the four sensors I needed:
const sensor01 = avaliacao.map((item) => item.dadosSensor01);
 const sensor02 = avaliacao.map((item) => item.dadosSensor02);
 const sensor03 = avaliacao.map((item) => item.dadosSensor03);
 const sensor04 = avaliacao.map((item) => item.dadosSensor04);
I don’t know if it’s best practice, but it solved the problem, I’m open to ideas if there’s a more efficient way :)– Saga Gemini