Setting up RTK (Redux Toolkit) for authentication (signup and login) in a large, complex Expo React Native app with a two-way use case (e.g., handling both user and admin roles) involves careful planning and structure. Below is a step-by-step guide to properly set up RTK for this scenario:
1. Project Setup
Ensure you have the necessary dependencies installed:
expo install @reduxjs/toolkit react-redux
2. Folder Structure
Organize your Redux code in a structured way. Here’s an example folder structure:
src/
├── features/
│ ├── auth/
│ │ ├── authSlice.js
│ │ ├── authAPI.js
│ │ ├── authSelectors.js
│ │ └── authMiddleware.js
│ ├── user/
│ │ └── userSlice.js
│ └── admin/
│ └── adminSlice.js
├── store.js
├── App.js
└── ...
3. Create the Auth Slice
Define the Redux slice for authentication in features/auth/authSlice.js:
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
user: null,
token: null,
role: null, // e.g., 'user' or 'admin'
isLoading: false,
error: null,
};
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
loginStart(state) {
state.isLoading = true;
state.error = null;
},
loginSuccess(state, action) {
state.isLoading = false;
state.user = action.payload.user;
state.token = action.payload.token;
state.role = action.payload.role;
},
loginFailure(state, action) {
state.isLoading = false;
state.error = action.payload;
},
logout(state) {
state.user = null;
state.token = null;
state.role = null;
},
},
});
export const { loginStart, loginSuccess, loginFailure, logout } = authSlice.actions;
export default authSlice.reducer;
4. Create API Calls
Use RTK Query or custom API calls in features/auth/authAPI.js:
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
export const loginUser = createAsyncThunk(
'auth/login',
async ({ email, password }, { rejectWithValue }) => {
try {
const response = await axios.post('/api/login', { email, password });
return response.data; // { user, token, role }
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
export const signupUser = createAsyncThunk(
'auth/signup',
async ({ email, password, role }, { rejectWithValue }) => {
try {
const response = await axios.post('/api/signup', { email, password, role });
return response.data; // { user, token, role }
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
5. Combine Reducers and Create Store
In store.js, combine all slices and create the Redux store:
import { configureStore } from '@reduxjs/toolkit';
import authReducer from './features/auth/authSlice';
import userReducer from './features/user/userSlice';
import adminReducer from './features/admin/adminSlice';
export const store = configureStore({
reducer: {
auth: authReducer,
user: userReducer,
admin: adminReducer,
},
});
6. Wrap App with Redux Provider
In App.js, wrap your app with the Redux provider:
import { Provider } from 'react-redux';
import { store } from './store';
export default function App() {
return (
<Provider store={store}>
{/* Your app components */}
</Provider>
);
}
7. Handle Two-Way Use Case
Use selectors and middleware to handle user roles:
-
Selectors: Create selectors to check the user's role in features/auth/authSelectors.js:
export const selectUserRole = (state) => state.auth.role;
export const selectIsAdmin = (state) => state.auth.role === 'admin';
-
Middleware: Use middleware to redirect or restrict access based on role:
import { useSelector } from 'react-redux';
import { selectUserRole } from './features/auth/authSelectors';
import { Redirect } from 'react-router-native'; // or your navigation library
const ProtectedRoute = ({ component: Component, allowedRoles, ...rest }) => {
const role = useSelector(selectUserRole);
if (!allowedRoles.includes(role)) {
return <Redirect to="/login" />;
}
return <Component {...rest} />;
};
8. Implement Signup and Login Components
Create components for signup and login, dispatching actions as needed:
import { useDispatch } from 'react-redux';
import { loginUser, signupUser } from './features/auth/authAPI';
const LoginScreen = () => {
const dispatch = useDispatch();
const handleLogin = (email, password) => {
dispatch(loginUser({ email, password }));
};
return (
// Your login form
);
};
const SignupScreen = () => {
const dispatch = useDispatch();
const handleSignup = (email, password, role) => {
dispatch(signupUser({ email, password, role }));
};
return (
// Your signup form
);
};
9. Persist Authentication State
Use libraries like @react-native-async-storage/async-storage to persist the token and user data:
import AsyncStorage from '@react-native-async-storage/async-storage';
const loadUserFromStorage = async () => {
const token = await AsyncStorage.getItem('token');
const user = await AsyncStorage.getItem('user');
const role = await AsyncStorage.getItem('role');
if (token && user && role) {
dispatch(loginSuccess({ user, token, role }));
}
};
10. Test and Debug
Test the authentication flow for both user and admin roles, ensuring proper state management and error handling.
Key Considerations for Large Apps
- Modularity: Keep slices and API calls modular and role-specific.
- Error Handling: Centralize error handling in middleware or slices.
- Performance: Optimize selectors and avoid unnecessary re-renders.
- Security: Securely store tokens (e.g., use SecureStore in Expo).
By following this structure, you can effectively manage authentication in a large, complex Expo React Native app with RTK.