2

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
4
  • You can access the array by its variable name. Commented Mar 13, 2021 at 11:49
  • 1
    Is the array filled after asynchronous call? Commented Mar 13, 2021 at 11:51
  • yes. I am setting this array from response of fetch. Commented Mar 13, 2021 at 11:52
  • 1
    please share the whole code Commented Mar 13, 2021 at 11:52

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.