CmchPt
CmchPt

Reputation: 39

How to Handle Error using try catch using React state with arrow functions

I am trying to implement some error validation with an arrow function. The catch works and I can print the errors, but I don't know how to link the errors I am printing inside errorsHandler to the other const where the form is for styling and warnings.

const errorsHandler = fieldErrors => {
  if (fieldErrors) {
    fieldErrors.forEach(err => {
      const errorFieldName= err.field;
      const errorDescription = err.message;
      console.log('Field',  errorFieldName, 'Description', errorDescription);
      // Field name Description name already exists
    });
  }
};

export const defaultGroupModel = {
  description: '',
  active: true,
  name: '',
}

const GroupFormModal = ({ editId, editGroup, onSave}) => {
  const [groupState, setGroupState] = useState(defaultGroupModel);
            
  useEffect(() => {
    if (editGroup) {
      setGroupState(editGroup);
    }
  }, [editGroup]);
            
  const handleChange = ({ target: { value, name} }) => {
    setGroupState({ ...groupState, [name]: value });
  };
        
  return (
    (...)
    <Form
      onSubmit={e => onSave(e, groupState)}
      onReset={onReset}
    >
    (...);

};

const mapDispatchToProps = dispatch => ({
  onSave: (e, group) => {
    e.preventDefault();
    if (group.id) {
      dispatch(updateGroup(group));
    } else {
      dispatch(createGroup(group)).catch(error => {
        errorsHandler(error.data.fieldErrors);
      });
    }
  },
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(GroupFormModal);

I have tried to create an [errorState, setErrorState] and use useEffect inside the errorsHandler but get "Invalid Hook" error. How can I have the handle inside the catch to be in the same context as the form?

Upvotes: -1

Views: 2420

Answers (1)

Dupocas
Dupocas

Reputation: 21317

There are few things you can do here. First, use mapDispatchToProps to wrap inside dispatch your action's creators (without then and catch)

const mapDispatchToProps = dispatch =>({
     updateGroup : group => dispatch(updateGroup(group)),
     createGroup : group => dispatch(createGroup(group))
})

Now you can set an internal state to reflect those errors

const Component = ({ updateGroup, createGroup }) =>{
    const [errors, setErrors] = useState(false)

    const onSave = (group,e) =>{
       createGroup(group)
           .then(res => console.log('everything ok'))
           .catch(err => setError(err) /* now you have the errors inside your component*/)
    }

    return <form onSubmit={ e => onSave(group,e)) }> /*...*/ </form>
}

Upvotes: 1

Related Questions