I used Redux and reselect, but I couldn't fetch data by connect
function from server. but if I use useSelector
and useEffect
hooks. it will work correctly and fetching data successfully.
but I need want to use connect
function instead of useSelector
.
I worked project in https://codesandbox.io and the source code is in below link.
source code link
sample code is here.
Thanks a lot
import { createSlice } from "@reduxjs/toolkit";
import api from "./api";
const initialUser = localStorage.getItem("user")
? JSON.parse(localStorage.getItem("user"))
: null;
// Slice
const slice = createSlice({
name: "user",
initialState: {
user: initialUser,
users: [],
isLoading: false,
error: false
},
reducers: {
startLoading: (state) => {
state.isLoading = false;
},
hasError: (state, action) => {
state.error = action.payload;
state.isLoading = false;
},
loginSuccess: (state, action) => {
state.user = action.payload;
localStorage.setItem("user", JSON.stringify(action.payload));
},
logoutSuccess: (state, action) => {
state.user = null;
localStorage.removeItem("user");
},
usersSuccess: (state, action) => {
state.users = action.payload;
state.isLoading = true;
},
getUsers: (state, action) => {
state.users = action.payload;
}
}
});
export default slice.reducer;
// Actions
const {
loginSuccess,
logoutSuccess,
usersSuccess,
startLoading,
hasError
} = slice.actions;
export const fetchUsers = () => async (dispatch) => {
dispatch(startLoading());
try {
await api
.get("/users")
.then((response) => dispatch(usersSuccess(response.data)));
} catch (e) {
dispatch(hasError(e.message));
}
};
export const login = ({ username, password }) => async (dispatch) => {
try {
// const res = await api.post('/api/auth/login/', { username, password })
dispatch(loginSuccess({ username }));
} catch (e) {
return console.error(e.message);
}
};
export const logout = () => async (dispatch) => {
try {
// const res = await api.post('/api/auth/logout/')
return dispatch(logoutSuccess());
} catch (e) {
return console.error(e.message);
}
};
export const selectUsers = (state) => state.user.users;
// App.js
const App = (props) => {
console.log("users", props.users)
return <div>sample</div>
}
const mapStateToProps = (state) => {
return { users: selectUsers(state) };
};
export default connect(mapStateToProps)(App);
Have a look at redux-api-middleware which provides a much better way of integrating data fetching in a redux workflow