react-nativeexpoexpo-router

Passing Object Using Expo Router


I need to pass an object from one screen to another using expo-router

I have a screen that shows a FlatList with items and a detail screen that would show more information about the item. The additional information is within the item object so another API call is not necessary.

The item model is as such:

{
  id: "123",
  title: "Some Title",
  imageURL: "https://...",
  ...other: "some other data"
}

using expo-router I believe I need to provide URL params, however, with the data that I have including an image URL it's not practical.

How do I go about just passing the object without URL parameters

Currently I get the item in a function as below;

const getDetails = (item) => {
    router.push({ pathname: `/details/${item.id}`, params: { item } });
};

How do I get this out in the second screen?


Solution

  • I've struggled with this myself too, and I haven't found any satisfactory solution. In your case you could slightly change the code that pushes the next screen:

    router.push({ pathname: `/details/${item.id}`, params: item }); // Remove the braces in params
    

    Then, following your example in the [id].tsx file you would have something like this:

    export default function ItemDetail() {
      const item = useLocalSearchParams();
    
      ...
    
    }
    

    The item object will have all the fields of the params parameter, plus the one of the route (e.g if the route is /{id}) it will have the id field as well. Unfortunately, since expo will pass every field as a query parameter in the URL, it is limited:

    It's not the best solution. What I've also thought about is just passing the id in the route and inside the component query the object from some memory cache.