0

The user data from json placeholder has the address as an object inside of the user object and I am trying to figure out how to display that data for learning and understanding purposes

import React, { useState, useEffect } from "react";
import "./App.css";

const App = () => {
  const [users, setUsers] = useState([]);
  const [user, setUser] = useState({});
  useEffect(() => {
    getUsers();
    getUser();
    //eslint-disable-next-line
  }, []);

  const getUsers = async () => {
    const res = await fetch("https://jsonplaceholder.typicode.com/users");
    const data = await res.json();
    setUsers(data);
  };

  const getUser = async () => {
    const res = await fetch("https://jsonplaceholder.typicode.com/users/1");
    const data = await res.json();
    setUser(data);
    console.log(data);
  };

  return (
    <div className="App">
      <h3 style={{ marginBottom: "5px" }}>
        Getting an Array of users from an Api
      </h3>
      <ul>
        {users.map(user => (
          <li style={{ marginBottom: "5px", paddingLeft: "10px" }}>
            Name:{user.name} <br />
            Email:{user.email}
          </li>
        ))}
      </ul>
      <div className="card" style={{ width: "400px" }}>
        <h3>Name: {user.name}</h3>
        <p>Email: {user.email}</p>

      </div>
    </div>
  );
};

export default App;

to this point everything works just fine

when I try to access the user address it throws an error

<div className="card" style={{ width: "400px" }}>
        <h3>Name: {user.name}</h3>
        <p>Email: {user.email}</p>
        <p>Address: {user.address.street}
      </div>

How do I access and object within an object?

1 Answer 1

2

You have to set init user.
Because of rendering null issue.

const defaultUser = {
    name: "",
    email: "",
    address: {
        street: ""
    }
};

const [users, setUsers] = useState([defaultUser]);
const [user, setUser] = useState(defaultUser);
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.