'How to use 'useDispatch' and 'useSelector' in class based component
I have one class where I'm using useDispatch and setting my data in reducer and I want to use my data in another class, like how I'm using useDispatch in functional component and using useSelector, I can fetch the the data from anywhere inside project, like that I want in class based component.
import { createSlice } from "@reduxjs/toolkit";
export const userSlice = createSlice({
name: "user", initialState: {
user: null,
},
reducers: {
setUser: (state, action) => {
state.user = action.payload.user;
},
logout: (state) => {
state.user = null;
},
},
});
export const { setUser, logout } = userSlice.actions;
export const selectUser = (state) => state.user;
export default userSlice.reducer;
// functional component One ..........................
const dispatch = useDispatch();
dispatch(setUser({ user: "om" }));
// functional component two ..........................
const selectcter = useSelector(selectUser);
console.log(selectcter);
` like that I want to use in class based component any help?
Solution 1:[1]
You can't mix React hooks inside class component. Either you change the class component into functional component with hooks, or use the Redux logic that fit to class components.
Solution 2:[2]
actually, useSelect and useDispatch is nothing but just a replacement of mapStateToProps and mapDispatchToProps which we pass in connect hoc when we try to connect our component with the redux store.
When you are working with the class component you can't use the useDispatch and useSelector because these are hooks that react-redux provides for use in the functional components for the same behavior which connect provides in the class component. So for your case have to look at how to use connect from react-redux and how to pass mapDispatchToProps and mapStateToProps if you are using the class component. here is documentation for connect
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Or Assayag |
| Solution 2 |
