# Meteor.js powered React hook for retrieving articles with error and loading state handling

> Learn how to handle error and loading state in a Meteor.js powered React app using a custom hook named useArticle. Get a concise and easy-to-understand…

- URL: https://graffino.com/til/meteorjs-powered-react-hook-for-retrieving-articles-with-error-and-loading-state-handling
- Author: Nick Ciolpan
- Channel: typescript
- Published: 2023-01-30
- Updated: 2024-01-31

The custom hook created uses Meteor's useTracker hook and the subscribe method to subscribe to the article publication, as well as the ArticlesCollection to find the article with the matching _id (which is the same as the slug in this case).


```
const useArticle = (slug: string): any => {
    const [error, setError] = useState<Error | null>(null)

    return useTracker(() => {
        const sub = Meteor.subscribe('article', { _id: slug })
        if (sub.ready()) {
            const article = ArticlesCollection.findOne({ _id: slug })
            if (article) {
                return {
                    loading: false,
                    error: null,
                    article,
                }
            } else {
                setError(new Error(`Article with slug "${slug}" not found`))
                return {
                    loading: false,
                    error,
                    article: undefined,
                }
            }
        } else {
            return {
                loading: true,
                error: null,
                article: undefined,
            }
        }
    }, [slug, setError])
}
```

This hook can be used in a React component to display the article, its loading state and error:



```
const Article = ({ slug }: { slug: string }) => {
    const { loading, error, article } = useArticle(slug)

    if (loading) {
        return <div>Loading...</div>
    }

    if (error) {
        return <div>Error: {error.message}</div>
    }

    return (
        <div>
            <h1>{article.title}</h1>
            <p>{article.body}</p>
        </div>
    )
}
```
