Can't map over a query in React

Asked
Active3 hr before
Viewed126 times

8 Answers

queryreact
90%

Query Render prop function,The render prop function that you pass to the children prop of Query is called with an object (QueryResult) that has the following properties. This object contains your query result, plus some helpful functions for refetching, dynamic polling, and pagination.,In other words, the render prop is a props object with the properties you need. The component is also only passed a single argument.

Using object destructuring you can access the data, loading, and error props.

function App() {
  return (
    <Query query={GET_POSTS_QUERY}>
      {({ data, loading, error }) => {
        if (loading) return <div>loading</div>
        if (error) return <div>error</div>

        return <ListPosts posts={data.allPosts} />

      }}
    </Query>
  )
}
load more v
88%

Finish up by creating a child component and passing your data from App.js, which is the parent component to your child component.,Assuming you already have a React app set up, the code below simulates a data object fetched from an API. This data will be passed down to your child component. For a refresher on this topic, read this guide.,Add this code to your parent component.

1 {
   2 "page": 1,
      3 "results": [{
            4 "poster_path": "/e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg",
            5 "adult": false,
            6 "overview": "From DC Comics comes the Suicide Squad, an antihero team of incarcerated supervillains who act as deniable assets for the United States government, undertaking high-risk black ops missions in exchange for commuted prison sentences.",
            7 "release_date": "2016-08-03",
            8 "genre_ids": [
               9 14,
               10 28,
               11 80
               12
            ],
            13 "id": 297761,
            14 "original_title": "Suicide Squad",
            15 "original_language": "en",
            16 "title": "Suicide Squad",
            17 "backdrop_path": "/ndlQ2Cuc3cjTL7lTynw6I4boP4S.jpg",
            18 "popularity": 48.261451,
            19 "vote_count": 1466,
            20 "video": false,
            21 "vote_average": 5.91
            22
         },
         23 {
            24 "poster_path": "/lFSSLTlFozwpaGlO31OoUeirBgQ.jpg",
               25 "adult": false,
               26 "overview": "The most dangerous former operative of the CIA is drawn out of hiding to uncover hidden truths about his past.",
               27 "release_date": "2016-07-27",
               28 "genre_ids": [
                  29 28,
                  30 53
                  31
               ],
               32 "id": 324668,
               33 "original_title": "Jason Bourne",
               34 "original_language": "en",
               35 "title": "Jason Bourne",
               36 "backdrop_path": "/AoT2YrJUJlg5vKE3iMOLvHlTd3m.jpg",
               37 "popularity": 30.690177,
               38 "vote_count": 649,
               39 "video": false,
               40 "vote_average": 5.25
            41
         },
         42 {
            43 "poster_path": "/hU0E130tsGdsYa4K9lc3Xrn5Wyt.jpg",
               44 "adult": false,
               45 "overview": "One year after outwitting the FBI and winning the public’s adulation with their mind-bending spectacles, the Four Horsemen resurface only to find themselves face to face with a new enemy who enlists them to pull off their most dangerous heist yet.",
               46 "release_date": "2016-06-02",
               47 "genre_ids": [
                  48 28,
                  49 12,
                  50 35,
                  51 80,
                  52 9648,
                  53 53
                  54
               ],
               55 "id": 291805,
               56 "original_title": "Now You See Me 2",
               57 "original_language": "en",
               58 "title": "Now You See Me 2",
               59 "backdrop_path": "/zrAO2OOa6s6dQMQ7zsUbDyIBrAP.jpg",
               60 "popularity": 29.737342,
               61 "vote_count": 684,
               62 "video": false,
               63 "vote_average": 6.64
            64
         }
         65
      ]
   66
   67
}
load more v
72%

TypeError: Cannot read property ‘map’ of undefined,React “see” the useState call and return us [undefined, fn].,React renders (invoking) our component.

// Just a data fetching function
const fetchURL = "https://jsonplaceholder.typicode.com/todos/";
const getItems = () => fetch(fetchURL).then(res => res.json());

function App() {
  const [items, setItems] = useState();

  useEffect(() => {
    getItems().then(data => setItems(data));
  }, []);

  return (
    <div>
      {items.map(item => (
        <div key={item.id}>{item.title}</div>
      ))}
    </div>
  );
}
load more v
65%

Pretag
 Pretag team - issue, fix, solve, resolve
75%

To set up the React Query Demo application on your machine, execute the following instructions:,In the next section, we’ll start looking at React Query’s main features.,isLoading: returns true while the asynchronous operation is running

Pretag
 Pretag team - issue, fix, solve, resolve
40%

That’s it! You should see the exact same screen as before.,Next, let’s implement the component that renders a list of links.,This hook returns three items that are relevant for our purposes at this point:

{
   feed {
      id
      links {
         id
         createdAt
         description
         url
      }
   }
}
load more v
22%

Using an array as a query key and a custom fetch that loops on the array is a fast to implement solution that comprises cache granularity (and possibly makes invalidation after mutations more complicated)., Using an array as a query key and a custom fetch that loops on the array is a fast to implement solution that comprises cache granularity (and possibly makes invalidation after mutations more complicated). ,Creating components that wrap useQuery ultimately solves the problem and gives cache granularity but makes the API slightly less intuitive to use.

const fetchData = async () => {
   const res = await fetch('my-api/data');
   const data = await res.json();
   const otherRes = await fetch(`my-api/other-data/${data.id}`);
   const otherData = await otherRes.json();
   return {
      ...data,
      ...otherData,
   };
};

const Component = () => {
   const {
      isLoading,
      error,
      isError,
      data
   } = useQuery('my-data', fetchData);
   // rest of component code
}
load more v
60%

The variable you are trying to map over is undefined. It will probably eventually be an array, but due to the asynchronous nature of React, you are experiencing at least one render when the variable is undefined.,This is one of the more common errors you will run into when starting out with React:,And now we have a pretty safe way of handling our async operation without getting the dreaded “cannot read property ‘map’ of undefined” error!

Cannot read property 'map' of undefined
load more v

Other "query-react" queries related to "Can't map over a query in React"