react-native-openfoodfacts
v0.1.0
Published
Hook to access OpenFoodFacts API from React Native
Maintainers
Readme
react-native-openfoodfacts
A simple and idiomatic wrapper to access the OpenFoodFacts API from React Native.
⚠️ Early stage project: the library is under active development.
Goals
- Provide hooks and functions to easily access OpenFoodFacts data in React Native apps
- Take inspiration from the structure and features of the Flutter openfoodfacts-dart library
- Keep the codebase clean, lightweight, and easily extensible
Installation
npm install react-native-openfoodfactsor
yarn add react-native-openfoodfactsSetup
Wrap your app (or the part of the app that uses OpenFoodFacts hooks) with the OpenFoodFactsProvider to enable React Query context:
import { OpenFoodFactsProvider } from "react-native-openfoodfacts";
export default function App() {
return (
<OpenFoodFactsProvider
config={{
environment: "staging", // or "production"
appName: "Your App Name",
version: "1.0.0",
contactEmail: "[email protected]",
cacheTime: 10, // optional, cache time in minutes (default: 10)
}}
>
{/* Your app components */}
</OpenFoodFactsProvider>
);
}Basic usage
import { useOpenFoodFacts } from "react-native-openfoodfacts";
export default function ProductScreen() {
const { getProduct } = useOpenFoodFacts();
const {
data: productResponse,
isLoading,
error,
} = getProduct("3017620422003"); // Example EAN
const product = productResponse?.product;
if (isLoading) return <Text>Loading...</Text>;
if (error) return <Text>Error: {error.message}</Text>;
if (!product) return <Text>Product not found</Text>;
return (
<View>
<Text>{product.product_name}</Text>
<Text>{product.brands}</Text>
</View>
);
}Passing options to getProduct
You can pass additional options (such as enabled, staleTime, etc.) to getProduct:
const { getProduct } = useOpenFoodFacts();
const {
data: productResponse,
isLoading,
error,
} = getProduct(ean, {
enabled: !!ean, // the query will only run if ean has a value
// staleTime: 5000, // you can set other React Query options as well
});Useful links
Contributions and feedback are welcome!
