Noble Polygon
Noble Polygon

Reputation: 806

Accessing nested JSON data with React Hooks & Props

I'm trying to access data further down into my JSON file. I am able to easily access data in the first two data sets in rows and area:

data.json

"rows": [
    {
      "uid":"001",
      "type": "Lorem ipsum",

      "area": [
        {

          "name": "London",
          "number": "12345",

          "wait": {
            "start": {
              "start_time": 1585129140,
              "delay": 300
            },
            "end": {
              "end_time": 1585130100,
              "delay": 300
            }
          },
          "in": 1585129140,
          "out": 1585130100,
        },

However when I try to access the data under wait which includes this block:

          "wait": {
            "start": {
              "start_time": 1585129140,
              "delay": 300
            },
            "end": {
              "end_time": 1585130100,
              "delay": 300
            }
          },

No data is getting returned on screen from my jsx file, but it is available in the console log

TimeTracker.jsx

const TimeTracker = (props) => {

  const trainTime = useState(props.data);
  console.log(props.data);
  
  
  return (
    <>
      <div className={style.timeLabel}>
      <div className={style.startTime}>{trainTime.start_time}</div>
      <div className={style.endTime}></div>
      </div>
    </>
    )
  };
  export default TimeTracker;

console.log

wait:
start:
start_time: 1585129140
delay: 300
__proto__: Object
end:
end_time: 1585130100
delay: 300
__proto__: Object
__proto__: Object

I've used the same pattern for passing props in other components and it works fine on the first two levels so I don't understand why it's not working. How do I get data from further in this JSON?

Upvotes: 0

Views: 307

Answers (2)

Eyal Ben-Ivri
Eyal Ben-Ivri

Reputation: 31

useState returns a tuple with the object and a function to set the value on the object. You probably need to change your component to something like this:

const TimeTracker = (props) => {

  const [trainTime, setTrainTime] = useState(props.data);
  console.log(props.data);


  return (
    <>
      <div className={style.timeLabel}>
      <div className={style.startTime}>{trainTime.start_time}</div>
      <div className={style.endTime}></div>
      </div>
    </>
    )
  };
  export default TimeTracker;

Upvotes: 1

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22875

A nested property can not be accessed by one level of a.b so instead of

<div className={style.startTime}>{trainTime.start_time}</div>

it should be

<div className={style.startTime}>{trainTime.wait.start.start_time}</div>

Upvotes: 0

Related Questions