How to access objects from array of data in react

67 views Asked by At

I have the following hook

import { useState, useEffect } from "react";
export default function FetchData(url) {
    const [data, setData] = useState([]);

    useEffect(() => {
        fetch(url)
            .then(response => response.json())
            .then(data => setData(data));
    }, []);

    return data;
}

I called this hook by writing the following code

const data = FetchData("https://hn.algolia.com/api/v1/search");

The previous API return the result with "hits" not directly in data

The problem was when I write the following code :

return (
          data.hits.map(hit =>
                    <div>{hit.title}</div>
                )

              );

I know that I can solve this problem by add "hits" in the hook , but I don't want to do this because I need the hook to be general . I need to manipulate the data in the calling part not in the hook . to be more specific , how can I access the hits data from the calling context not from the hook .

1

There are 1 answers

2
PrakashT On

Try this line:

 return (
           data && data.hits && data.hits.map(hit => <div>{hit.title}</div>)
         );