react promise in functional component

岁酱吖の 提交于 2021-01-29 05:55:53

问题


I have a functional component in which I want to save the data in my inputs form sending them with saveForm method to my java API.

How can I read the response of this promise props.saveForm (in order to look for potentials server errors) in a functional component? I've read that in these cases it must be used useEffect hooks..but If I move my handleSubmitForm() inside useEffect than I can't call it when the onSubmit event is thrown.

Please enlight me. Thank you for your wisdom.

Code I found in others questions :

useEffect(() => {
    const saveForm= async () => {  //!but like this is not fired on the onSubmit event!
      const result = await axios.get(`/api/formpage/${id}`);
      setData(result.data.inputs); 
    };
    fetchInitialData();
}, []);

My code right now:

const handleSubmitForm= (e) => {
   e.preventDefault(); 
   props.saveForm(newData, props.history);
};


return (
<div>
  <Styles>
    <form onSubmit={handleSubmitForm}>
        .....
         <input ..... />
         <input ..... />
        .....
    </form>
  </Styles>
</div>
);
  

actions.js:

export const saveForm= (newData) => async (dispatch) => {
  try {
   const res = await axios.post("/api/formexample", newData);
   dispatch({//this dispatch is to clean past errors if now are resolved
   type: GET_ERRORS,
   payload: {},
});
} catch (err) {
   dispatch({
   type: GET_ERRORS,
   payload: err.response.data,
});
}
};

回答1:


You don't have to put your handleSubmitForm in a useEffect. This function is being used in response to a button click, so it's not an effect.

You can make your function handleSubmitForm async and do an await.

const handleSubmitForm = async (e) => {
   e.preventDefault();
   const result = await callValidation(data));

   // check your result
};

I'm not sure how you are checking your validation, so this is just an example.



来源:https://stackoverflow.com/questions/63586906/react-promise-in-functional-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!