Search code examples
reactjsreduxuse-effect

useEffect redux state changed, but data not displayed


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));
      });
  };
};

Solution

  • 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>
        </>
      );
    };