🚀 Redux Authentication with Mock API | Login & Logout with Redux & Reqres
Redux Authentication with Mock API: A Step-by-Step Guide
In modern web applications, managing user authentication is a critical functionality. In this tutorial, we will explore how to implement user authentication using Redux, a predictable state container for JavaScript apps, and a mock API service called Reqres. We'll be building a simple login and logout system that demonstrates how to manage authentication state effectively.
Prerequisites
Before we get started, make sure you have the following installed on your machine:
- Node.js
- npm (Node Package Manager)
- A basic understanding of JavaScript, React, and Redux
Setting Up the Project
Step 1: Create a React App
First, we will create a new React application using the Create React App command:
npx create-react-app redux-authentication
cd redux-authentication
Step 2: Install Redux and React-Redux
Next, we need to install Redux and React-Redux, which will allow us to manage our application state:
npm install redux react-redux
Step 3: Set Up Redux Store
Create a folder named redux in the src directory. Inside this folder, create a file called store.js. This file will contain our Redux store configuration.
// src/redux/store.js
import { createStore, combineReducers } from 'redux';
import authReducer from './authReducer';
const rootReducer = combineReducers({
auth: authReducer,
});
const store = createStore(rootReducer);
export default store;
Step 4: Create Auth Reducer
Now, we will create an authReducer.js file in the redux folder. This reducer will manage the authentication state.
// src/redux/authReducer.js
const initialState = {
isAuthenticated: false,
user: null,
};
const authReducer = (state = initialState, action) => {
switch (action.type) {
case 'LOGIN':
return {
...state,
isAuthenticated: true,
user: action.payload,
};
case 'LOGOUT':
return initialState;
default:
return state;
}
};
export default authReducer;
Step 5: Provide the Redux Store
Next, we need to wrap our application with the Redux Provider. Open src/index.js and set it up as follows:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './redux/store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Implementing Login and Logout Functionality
Step 6: Create Login Component
Next, we will create a simple login form. Create a file named Login.js in the src directory.
// src/Login.js
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
const Login = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const dispatch = useDispatch();
const handleLogin = async (e) => {
e.preventDefault();
const response = await fetch('https://reqres.in/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
});
const data = await response.json();
if (response.ok) {
dispatch({ type: 'LOGIN', payload: data });
} else {
alert('Login failed. Please check your credentials.');
}
};
return (
<form onSubmit={handleLogin}>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
<button type="submit">Login</button>
</form>
);
};
export default Login;
Step 7: Create Logout Component
Next, let’s create a simple logout button. Create a file named Logout.js.
// src/Logout.js
import React from 'react';
import { useDispatch } from 'react-redux';
const Logout = () => {
const dispatch = useDispatch();
const handleLogout = () => {
dispatch({ type: 'LOGOUT' });
};
return <button onClick={handleLogout}>Logout</button>;
};
export default Logout;
Step 8: Update App Component
Finally, we need to modify the App.js file to include the login and logout components based on the authentication state.
// src/App.js
import React from 'react';
import { useSelector } from 'react-redux';
import Login from './Login';
import Logout from './Logout';
const App = () => {
const isAuthenticated = useSelector((state) => state.auth.isAuthenticated);
return (
<div>
{isAuthenticated ? <Logout /> : <Login />}
</div>
);
};
export default App;
Running the Application
Now that we have implemented the authentication system, let's run our application:
npm start
You should see the login form on your browser. Enter the credentials (you can use any email, and for password input password should work based on the mock API) to log in, and then click the logout button to log out.
Conclusion
In this tutorial, we have successfully set up a simple authentication system using Redux and a mock API from Reqres. You learned how to create a Redux store, manage authentication state with reducers, and dispatch actions to log in and out users. This foundational knowledge can be extended to build more complex authentication systems, including registration, password recovery, and integrating with real-world APIs.
Feel free to experiment further and enhance this boilerplate code to fit your application's needs. Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment