0

I am new to React, I am trying to implement some error validation with a react arrow function but got no luck all day. The catch works and I can print the errors, but I dont 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. How can I have the handle inside the catch to be in the same context as the form ?

Thank you in advance

CmchPt
  • 41
  • 7
  • Note that, try-catch doesn't work for React components since they're declarative. For same purpose, React has a concept of Error boundaries. Do look into that. – pritam Sep 24 '19 at 19:39

1 Answers1

1

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>
}
Dupocas
  • 20,285
  • 6
  • 38
  • 56
  • Is this the "only" way ? I mean, was it possible to also dispatch errorsHandler() inside the catch I read the error from props in the main component ? – CmchPt Sep 25 '19 at 13:59
  • In React nothing it's never the only way. Yes you can do using `redux` too – Dupocas Sep 25 '19 at 20:00