How to get related object from the cache

Hello there!

I have this query paymets to get all the payments for the user, the object has a connectin with student.

When I render the payments I have the id of the student, but I need the rest of the fields.

I don’t want to fetch again for the data that it’s already in the cache.

So, how to connect the id of the student inside the payments query ?

query payments{
   id
  ...restOfData
   student {
      id
   }
}

query allStudents {
   id
   name
   email
}

The render in React:

return data.payments.map((aPayment) => {
     return(
         <div>
             // Render RestOfData for each Payment.
             // Inside this map I have the id of the student, and need to access the rest of the fields.
         </div>
     );
});

I have this pattern all over the app.

The regular way would be to query for your payments and students like this:

query {
    payments {
        id
        student {
            id
        } 
    } 
    allStudents {
        id
        // all the additional data 
    } 
} 

And then inside your map:

return data.payments.map((payment) => {
    const student = data.allStudents.find(({ id }) => id === payment.student.id);

    return (
        <div key={payment.id}>
            // render data from `student`
        </div>
    );
});

If you do this all over your app (like I do), this can get very verbose very quickly, which is why I’ve added it as an automated feature to my apollo-augmented-hooks library. It’s called cache inflation, and here is a short guide on how it works.

2 Likes