Search code examples
javascriptreactjsredux

Conditional statement for testing an empty object not executing


I'm trying to show a success feedback once the users are registered without error. There is an errors redux reducer object which stores errors that come from the back end. And the if statement is supposed to give the success feedback if the errors object is empty, it displays the errors if there are any, it also registers the users if there is none, but it doesn't seem to execute the if(props.errors === {}) block.

  function onSubmit(e) {
    e.preventDefault();
    const newUser = {
      fname: fname,
      lname: lname,
      phone: phone,
      email: email,
      password: password,
    };
    dispatch(register(newUser));
    if (props.errors === {}) { //This block is not executed
      setSnackOpen(true);
      setFname('');
      setLname('');
      setEmail('');
      setPhone('');
      setPassword('');
    }
    console.log('errors :' + props.errors);  //logs 'errors : [object, object]'
  }

The errors reducer:

import { GET_ERRORS } from '../actionTypes/actionTypes';

const initialState = {
};

export const errorReducer = (state = initialState, action) => {
  switch (action.type) {
    case GET_ERRORS:
      return action.payload
    default:
      return initialState;
  }
};

Solution

  • Because you are comparing props.errors with {} new empty object so even though both are empty they are pointing to different memory location so if condition will return false for the statement if(props.errors === {})

    You can check length of the props.errors like

    if(!Object.keys(props.errors).length)