0

I am writing a simple react app that makes an api call to reddit.

In sorting through the data I am trying to target the value for the first element in its media_metadata object, the first element is an id that is unique, so I am trying to get the key for the first object (I only need 1 key, value pair from each post as I only need to display the first image which is what the media_metadata corresponds to). so as they are unique id's I am trying to use Object.keys, but when I try to write it such as in the code below, it just doesnt seem to work.

tile.js

    if(fulldata.media_metadata) {
        let media = fulldata.media_metadata
        let firstKey = Object.keys(media)[0]
        console.log('media', media)
        console.log('second try', media.vz3t8xwjirt91.status)
        console.log('trying', media.firstKey.status)
    }

in the above snipet the 'second-try' console log prints fine (I just went to the developer tools to extract one of the id's for testing purposes to compare against using Object.keys as a sanity check) however when using Object.keys in its place I get a type error: Uncaught TypeError: Cannot read properties of undefined (reading 'status').

can I not use Object.keys in this manner? what are the alternatives.

below is some other relevant code such as in the api calls:

TileList.js

import React, { useState, useContext } from "react";
import Tile from "./Tile";
import { Context } from "../Context"


export default function TileList() {

    const { apiData } = useContext(Context)

    // const tileItemElements = apiData.map(item => ())

    const tileItemElements = apiData.map(item => (
        <Tile
            key={item.data.id}
            img={item.data.thumbnail}
            fulldata={item.data|| "" }
            title={item.data.title}
            id={item.data.id}
            comments={item.data.num_comments}
            ups={item.data.ups}
            author={item.data.author}
            date={item.data.created}
            subreddit={item.data.subreddit}

        />
    ))


    return (
        <>
            <div className="tilelist">
                {tileItemElements}

            </div>
        </>

    )
}

Context.js

import React, { useState, useEffect } from "react"
import { mockData, mockCommentData } from "./resources/data"

const Context = React.createContext()

function ContextProvider({ children }) {

    const [apiData, setApiData] = useState([])
    const [commentData, setCommentData] = useState([])
    const [mockApiData, setMockApiData] = useState([])
    const [mockApiCommentData, setMockApiCommentData] = useState([])
    const [hasSearchTerm, setHasSeartchTerm] = useState(false)
    const [searchData, setSearchData] = useState("")
    const [submitData, setSubmitData] = useState("")
    const [subReddit, setSubReddit] = useState("Home")


    useEffect(() => {
        fetch(`https://www.reddit.com/r/${subReddit}/hot.json`)
            .then(res => res.json())
            .then(item => setApiData(item.data.children))
            .catch((err) => {
                console.log('error error')
            });
    }, [subReddit])

    

    // useEffect(() => {
    //     fetch('https://www.reddit.com/r/worldnews/comments/y1ppwm.json')
    //         .then(res => res.json())
    //         .then(item => setCommentData(item[1].data.children))
    //         .catch((err) => {
    //             console.log('error error')
    //         });
    // }, [])

    console.log('apidata', apiData)
    // console.log('commentdata', commentData)



    function handleSearchChange(event) {
        const { value } = event.target
        setSearchData(value)
    }

    function handleSearchSubmit(event) {
        event.preventDefault()
        setSubmitData(searchData)

    }

    function handleSubRedditChange(event) {
        setSubReddit(event.target.value)
    }

    console.log('subreddit', subReddit)

    return (
        <Context.Provider value={{
            apiData,
            mockApiData,
            mockApiCommentData,
            hasSearchTerm,
            setHasSeartchTerm,
            handleSearchChange,
            searchData,
            handleSearchSubmit,
            submitData,
            handleSubRedditChange
        }} >
            {children}
        </Context.Provider>
    )
}


export { ContextProvider, Context }

the developer tools of the media_metadata that I am trying to target Text

  • 2
    You confused `media.firstKey` and `media[firstKey]`. Btw the even easier way would be to use `Object.values` instead of `Object.keys`: `Object.values(media)[0].status` – CherryDT Oct 15 '22 at 11:29

0 Answers0