Reputation: 1628
I have an array categoryDataString
[{"ID":"1","Category":"first"},
{"ID":"2","Category":"second"},
{"ID":"3","Category":"third"}]
I want to access the specific value from the array. like the name of the 2nd category.
I tried 1st
console.log(categoryDataString[0].ID)
result
undefined
2nd
console.log(categoryDataString)
result
[{"ID":"1","Category":"first"},{"ID":"2","Category":"second"},{"ID":"3","Category":"third"}]
This is my code
const categoryDataString = JSON.stringify(categoryData)
const categoryData = useCategoryData()
useEffect(() => {
setDataLoad(DataLoaded + 1)
setSelected(categoryDataString.Category)
console.log(categoryDataString[0].ID)
console.log(categoryDataString)
}, [categoryData])
This is my Itemdata.js
import React, { useState, useEffect } from 'react'
import { View, Text, StyleSheet } from 'react-native'
export const useCategoryData = (props) => {
const [Category, setCategory] = useState('')
useEffect(() => {
fetch('https://www.amrutras.com/Category.php')
.then((response) => response.json())
.then((responseJson) => {
{
setCategory(responseJson)
// responseJson.map((item) => Alert.alert(item.Name))
}
// Showing response message coming from server after inserting records.
})
.catch((error) => {
console.error(error)
})
}, [])
return Category
}
export default useCategoryData
Upvotes: 2
Views: 1966
Reputation: 838
I think you get undefined because categoryDataString is well, a string. so you would need to converty it to an object then access the properties as such:
const categoryDataObject = JSON.parse(categoryDataString);
console.log(categoryDataObject[0].ID)
you could also try accessing the categoryData without needing to convert it to a json string in the first place, so:
console.log(categoryData[0].ID)
Upvotes: 2