0
votes

I am using the following code to get the redux state data updated on the page. Redux State is updated as well as the data is printed on the console. But the data is is not rendered on the page.

When I am using this statement, it gives error employee[0] is undefined. const { id, empno, firstname } = employee[0];

const EmployeeDetails = ({match}) => {
  const dispatch = useDispatch();

  const employee = useSelector(state => state.employee.data);
  useEffect(() => {
    let employeeobj = { id: parseInt(match.params.id, 10) };
    dispatch(singleEmployee(employeeobj));
  }, [match.params.id, dispatch]);

     const { id, empno, firstname } = employee[0];

  return (
    <>
    <h2> Employee Id: {id}</h2>
    </>);
};

EmployeeDetails.propTypes = {
  match: propTypes.object};

export default EmployeeDetails;
const singleEmployee = (empobj) => {
  return dispatch => {
    dispatch(singleEmployeeBegin());
    axios
      .post(config.APIURL.employee.displaydetail, empobj)
      .then(response => {
        const employee = response.data;
        dispatch(singleEmployeeSuccess(employee));
      })
      .catch(error => {
        dispatch(singleEmployeeFailure(error.message));
      });
  };
};
1
It helps if you look at the redux devtools and see what actions are dispatched and what changes they make to the state. You also log employee before setting them. Not only is singleEmployee action asynchronous but the effect dispatching it will run after first render.HMR
adding codesandbox link of reproducible issue could help as well.hafiz ali
Redux state is updated. On Console, it shows data. But Not showing data on the page.Rajesh Gupta

1 Answers

1
votes

try to log the employee data to see what's inside of it and the change your code to this so you won't get an error:


const EmployeeDetails = ({ match }) => {
  const dispatch = useDispatch();
  const employee = useSelector((state) => state.employee.data);

  useEffect(() => {
    let employeeobj = { id: parseInt(match.params.id, 10) };
    dispatch(singleEmployee(employeeobj));
    // you don't need dispatch in your dependency array because it won't be change
  }, [match.params.id]);

  // just check for employee[0] and if it's not exist you won't get an error
  const { id, empno, firstname } = employee.length ? employee[0] : {};

  return (
    <>
      <h2> Employee Id: {id}</h2>
    </>
  );
};