i have trying to using UseSelector to get data in a redux, but it's alwas returned undefined, but when i try log console.log teh variable that i wanted to get in redux it's get updated, but when i try console log the useSelector it's returned undefined
code Redux :
export const EXCHAHNGETOSECOND = 'EXCHANGETOSECOND'
export const exchangetosecwork = (hour,minute,second) =>({
type:EXCHAHNGETOSECOND,
payloadhourwork : hour,
payloadminutework : minute,
payloadsecondwork : second
})
let initialState ={
resultWorkinSecond : 0
}
export const mainReducer = (state=initialState, action) =>{
switch (action.type) {
case EXCHAHNGETOSECOND:
const hourTosecond = action.payloadhourwork * 3600
const minuteTosecond = action.payloadminutework * 60
const res = hourTosecond minuteTosecond action.payloadsecondwork
state.resultWorkinSecond = res
console.log(state.resultWorkinSecond);
return state.resultWorkinSecond
default:
return state
}
}
export default mainReducer
store redux :
import { createStore } from "redux";
import mainReducer from "./redux";
import AsyncStorage from '@react-native-async-storage/async-storage';
import { persistStore, persistReducer } from 'redux-persist'
const persistConfig={
key:'root',
storage:AsyncStorage,
};
const persistedReducer = persistReducer(persistConfig,mainReducer)
export default() => {
let store = createStore(persistedReducer)
let persistor = persistStore(store)
return{ store, persistor }
}
myConsole log test:
const resWorkinSec = useSelector((state)=>state.resultWorkinSecond)
<Pressable onPress={()=>{
dispatch(exchangetosecwork(hour,minute,second))
console.log(resWorkinSec)
}}>
[console log result 1
CodePudding user response:
Your reducer has multiple bugs:
- it does an assignment, changing state. This is not allowed in legacy Redux reducers, but only in modern Redux using
createSlice
return state.resultWorkinSecond
then even changes the full state structure.
Correct legacy Redux code would look like this:
export const mainReducer = (state=initialState, action) =>{
switch (action.type) {
case EXCHAHNGETOSECOND:
const hourTosecond = action.payloadhourwork * 3600
const minuteTosecond = action.payloadminutework * 60
const res = hourTosecond minuteTosecond action.payloadsecondwork
return { ...state, resultWorkinSecond: res }
default:
return state
}
}
All that said, this is an old style of Redux that we do not recommend any more since 2019. It is more complicated, and error-prone. And about 4 times the code modern Redux would be. Modern Redux does not use switch..case reducers, ACTION_TYPES, immtuable reducer logic (like you needed to do here), createStore
and the likes.
I would highly recommend you drop what you are doing for a moment and go through the official Redux tutorial.