'React Redux State on direct link call
I´m using Redux for a Global State Object currentUser.
Everything is working as expected but I´m quite unsure on how to handle state when nothing yet is there.
Means I try to set the State dynamic on direct link call (e.g. localhost:port/users/id) if current User is empty on this time but I get an Error "Cannot read properties of undefined (reading State).
API Call is working as expected aswell.
Code:
Call Fetch if currentUser is not set (which is the case on direct link call):
const currentUser = useSelector((state => state.getCurrentUser.user))
const dispatch = useDispatch()
useEffect(() => {
restAPI("get", hostAPI + window.location.pathname)
.then(data => setHours(data))
.catch(() => console.log("Something went wrong...."))
if(!currentUser.id) {
let num = window.location.pathname.match(/\d+/g);
dispatch(getCurrentUser())
}
}, [])
if(currentUser.length) {
render(
....
)
}
getCurrentUserSlice:
import {createSlice} from "@reduxjs/toolkit";
import {createAsyncThunk} from "@reduxjs/toolkit";
import {hostAPI} from "../../api/env_dev";
import {restAPI} from "../../api/restAPI";
import {currentUserSlice} from "../user/currentUserSlice";
export const getCurrentUser = createAsyncThunk(
"users/getCurrentUser",
async (dispatch, getState) => {
return await restAPI("get", hostAPI + "/profile/1")
}
)
const getCurrentUserSlice = createSlice({
name: "getCurrentUser",
initialState: {
user: [""],
status: null
},
reducers: {
addCurrentUser: (state, action) => {
state.user = action.payload
}
},
extraReducers: {
[getCurrentUser.pending]: (state, action) => {
state.status = "loading"
},
[getCurrentUser.fulfilled]: (state, action) => {
state.status = "success";
state.user = action.payload
},
[getCurrentUser.rejected]: (state, action) => {
state.status = "failed"
}
}
})
export const {addCurrentUser} = getCurrentUserSlice.actions
export default getCurrentUserSlice.reducer;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
