skip to Main Content

I have an error
Cnnot destructure property ‘status’ of ‘(0 , react_redux__WEBPACK_IMPORTED_MODULE_1__.useSelector)(…)’ as it is undefined.

I’m trying to handle errors that come from the server with "toast"
But when I wrote this code in RegisterPage.jsx, the page doesn’t even open for me.

RegisterPage.jsx

const { status } = useSelector(state => state.auth )

    useEffect(() => {
        if (status) {
            toast(status)
        }
    }, [status])

store.js

export const store = configureStore({
    reducer:{
        auth: authSlice
    },
})

authSlice.js

const initialState = {
    user: null,
    token: null,
    isLoading: false,
    status: null,
}

2

Answers


  1. It’s look like, something is wrong with the registering the slice. Change your code with below one and test.

    Slice.js

    import { createSlice } from '@reduxjs/toolkit';
    
    const initialState = {
        user: null,
        token: null,
        isLoading: false,
        status: null,
    }
    
    const slice = createSlice({
      name: 'authSlice',
      initialState,
      reducers: {
        getUsers(state, action) {
          const { data, meta = {} } = action.payload;
          state.users = data;
        },
      }
    });
    
    export const { authSlice } = slice;
    
    
    export default slice;
    
    
    const { status = 'Something' } = useSelector(state => state.auth )
    

    It’s look like state.auth is not returning anything.

    Login or Signup to reply.
  2. You can solve this by doing the following

    const auth = useSelector(state => state.auth )
    
        useEffect(() => {
            if (auth?.status) {
                toast(auth?.status)
            }
        }, [auth?.status])
    

    Most likely you are running react in strict mode and it renders twice/multiple times in strict mode. So, At first render you receive undefined at the end of these render you get the correct values.

    Also, It runs twice/multiple times to detect side effects for you, it can help you spot errors by making it a little more deterministic.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search