M.S.Naidu
M.S.Naidu

Reputation: 2289

Passing String value through Props returned from useSelector Hook

I am working on ReactJS modal dialog and bind the values from redux slice through the useSelector hook. Currently I have two functions which are already dispatching using useDispatch hook and setting the props with 2 functions(onCancelHandler, submitHandler). Here I need to keep one more field which is string value(userName) and tried to keep that and usig the string value approvedUser in DeleteUserModalContent through the props. Initially I am able to get the value from props in DeleteUserModalContent component but when submitHandler is executed the following error is occured.

Can't read property 'userName' which is undefined

Error at this line: const approvedUser: string = selectedUser.userName;

Can any one tell me what is wrong here?

Thanks in Advance

Code Snippet:

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Modal } from '@material-ui/core';
import { AppState } from 'store/rootReducer';
import { hideModal } from 'store/common/modalSlice';
import { submitAction } from 'store/user-actions';
import { DeleteUserModalContent } from './DeleteUserModalContent';

export const DeleteUserModal: React.FC<{}> = () => {
  const dispatch = useDispatch();

  const selectedUser = useSelector((state: AppState) => {
    const selectedUserId =
      state.selectUserSlice.selectedUsers[0];
    return state.userState[selectedUserId];
  });

  const onCancelHandler = () => {
    dispatch(hideModal());
  };

  const submitHandler = () => {
    dispatch(
      submitAction(selectedUser.userName)
    );
  };

  const approvedUser: string = selectedUser.userName;
  console.log(selectedUser.userName);


  const props = {
    onResetHandler,
    submitHandler,
    approvedUser
  };

  return (
    <Modal>
      <>
        <DeleteUserModalContent {...props} />
      </>
    </Modal>
  );
};

Upvotes: 0

Views: 410

Answers (1)

M.S.Naidu
M.S.Naidu

Reputation: 2289

When we use the returned value from the useSelector hook and use the same in other component DeleteUserModalContent by setting into props. Here we are able to use the approvedUser value initially but when submitHandler function is dispatched selectedUser.userName value becomes undefined, So we can put the condition check below:

const approvedUser: string = selectedUser?.userName 

to avoid the above mentioned error.

Upvotes: 0

Related Questions