Home > Back-end >  redux toolkit can't bring the value from my action
redux toolkit can't bring the value from my action

Time:07-10

I try to dispatch an action that will return a value of stored in the asyncStorage, its a react native project , and I am using redux toolkit , I don't know why its always returning the initialized value of the state, user always null , could ypu please help , here is my code :

//store
    export const store = configureStore({
      reducer: {
        myuser : userAuth
      },
    })

===============

    import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
    
    const initialState = {
    user: null,
    isError: false,
    isSuccess: false,
    isLoading: false,
    message: '',
  }

    export const getUser = createAsyncThunk('userlog/getUser',   ( thunkAPI) => {
        return  AsyncStorage.getItem('myuser')
        .then((data) =>  data )
        })
    
    export const userSlice = createSlice({
      name: 'userlog',
      initialState,
      extraReducers : (builder) =>{
          builder.addCase(getUser.pending , state =>{
            state.isLoading = true
          })
          builder.addCase(getUser.fulfilled , (state, action) =>{
            state.user = action.payload
            state.isLoading = false
          })
          builder.addCase(getUser.rejected , state =>{
            state.isLoading = false
          })
      }
    
    })
    
    export default userSlice.reducer

and in my app.js that's how I am dispatching the action :

import {getUser} from '../../app/features/user/userSlice'


  const { user, isLoading, isError, isSuccess, message } = useSelector(
    (state) => state.myuser
  )

   useEffect(()=>{          

    dispatch(getUser())
})

CodePudding user response:

destructure your getUser in props like this

 const { user, isLoading, isError, isSuccess, getUser , message } = useSelector(
    (state) => state.myuser
  )

CodePudding user response:

with useSelector you are trying to get state values from user.myuser which I don't see in your state

try

  const { user, isLoading, isError, isSuccess, message } = useSelector(
    (state) => state
  )

or

  const user = useSelector((state) => state.user)

for getting the user

edit after added sourcecode to question: there is a mismatch between the name of the key in your store and the name in creacte slice. in the store it's called myuser and in createSlice it's called userLog. You should change userLog to myuser

  • Related