0

I'm fetching this JSON from an API:

{
  "data": {
    "email": "test@tre.com",
    "inserted_at": "2021-03-30T15:37:06",
    "links": [
      {
        "id": 1,
        "title": "My link title",
        "url": "http://google.com"
      },
      {
        "id": 2,
        "title": "My Youube title",
        "url": "http://youtube.com"
      }
    ]
  }
}

I'm fetching it this way using Hooks:

export default function Notes() {
  const [json, setJSON] = useState([]);

  useEffect(() => {
    fetch("http://localhost:4000/api/users/1", {
      method: "GET"
    })
      .then((response) => response.json())
      .then((json) => {
        // console.log(data);
        setJSON(json);
      })
      .catch((err) => {
        console.error(err);
      });
  }, [setJSON]);

Then I try to show it like this:

return (
    <>
      <div className="content">
          {JSON.stringify(json)}
          <h1>{json.email}</h1>
</div>
</>
);

The line {JSON.stringify(json)} shows the JSON.

But the line <h1>{json.email}</h1> doesn't show anything.

I don't know why that happens and how can I access my variables.

Thanks . I appreciate any help

manuel.menendez
  • 185
  • 3
  • 11

2 Answers2

2

Is the data in the form of an array or an object?

You defined the initial state as and array ad hence you cannot do

// you can't do json.email if you expect the response as and array


 const [json, setJSON] = useState([]);

change it to

 const [json, setJSON] = useState({});

if it is an object. Then in the template do

{json.data && <h1>{json.data.email}</h1>}
ArrowHead
  • 609
  • 5
  • 16
1
<h1>{json.data && json.data.email}</h1>

instead of

<h1>{json.email}</h1>
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Bogdan Pryvalov
  • 156
  • 1
  • 7