Repository pattern
- React Native course
- Expert
- Lesson 16/47
- 5 min
Learn the repository pattern.
Repository pattern
The repository pattern manages data access in a single place. The domain logic does not call fetch or the database directly; it asks a Repository for data.
This way, if the data source changes (REST to GraphQL), only the repository is updated; the domain is unaffected. In tests the repository is mocked; no real API call happens.
Mockability
The biggest gain of the repository pattern is testability. Instead of a real API call, a fake (mock) repository is supplied; the test runs fast and stable.
The mock repository implements the same interface; when getUser is called, it returns a fixed object. This way the test does not depend on network or server state.
Practice Write ApiUserRepository
Write an ApiUserRepository class or object. It should implement the UserRepository interface; its getUser(id) method calls fetch. Export it with export.
Starter code
// Define ApiUserRepository here
export default ApiUserRepository;Sample solution
// Define ApiUserRepository here
const ApiUserRepository = {
getUser: (id) => fetch(`/api/users/${id}`).then(r => r.json())
};
export default ApiUserRepository;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the repository pattern abstract?
- The data source
- UI components
- Style computation
- Navigation flow Correct answer
Explanation: The repository abstracts the data source.
2 Write the mock repository return
const mockRepo = {
getUser: async (id) => { return ____ }
};
const mockRepo = {
getUser: async (id) => { return { id, name: 'Ali' } }
};
Explanation: The mock returns a fixed object.
3 Match the repository pieces
| Term | Meaning |
|---|---|
Repository |
Data access abstraction |
Interface |
Contract |
Mock |
Fake data |
Domain |
Business logic |