Author - Maniraj Singh Post Views - 73 views
React Js

Redux in React Js

Redux is commonly used to maintain and update data globally in the react Js application. By using redux we don’t need to pass data from one component to another component.

Install redux

npm install @reduxjs/toolkit react-redux

Provide the Redux Store to React

Once the redux store is created then, we have to pass the store to the whole project. This can be done by the provider in the app.js file where all the routes of the application are defined.

import { Provider } from "react-redux";

<Provider store={store}>
<App />
</Provider>

Dispatch will be used to store data in the redux store.
dispatch(login(newUserData))

Defined Action:
import {
LOGIN_SUCCESS,
} from "../../constants/type";
export const login = users => {
return {
type: LOGIN_SUCCESS,
payload: users
};
};

Define constant
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";

Reducer: It takes two arguments, state, and actions and returns updated data.
import {
LOGIN_SUCCESS,
LOGOUT
} from "../../constants/type";
const user = JSON.parse(localStorage.getItem("user"));
const initialState = user
? { isLoggedIn: true, user }
: { isLoggedIn: false, isLoading: false, user: null, errors: {} };
export default function(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case LOGIN_SUCCESS:
return {
...state,
isLoggedIn: true,
isLoading: false,
user: payload,
errors: {}
};
case LOGOUT:
return {
...state,
isLoggedIn: false,
user: null,
errors: {}
};
default:
return state;
}
}

Read user data with useSelector in other components from the redux store.

import { useSelector } from "react-redux";
const user = useSelector(state => state.auth.user);

You can also define multiple actions and reducers for different functionality (rootReducer.js file).
import { combineReducers } from "redux";
import authReducer from "./auth/reducer";
import createListing from "./createListing/reducer";
const reducer = combineReducers({
auth: authReducer,
listing: createListing
});
export default reducer;

Study Section provides a big list of certification exams through its online platform. The French Certification Exam can help you to certify your skills to communicate in the French language. Whether you are new to the language or you are an expert in it, this French certification exam can test the ability of anybody’s command over the French language.

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri