Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

javascript - React: Invalid hook call in SubmitForm, custom hook useSendFormData

I made a hook useSendFormData , when i use it i get Invalid hook call.

Hook takes

  • data from SubmitForm

  • url:string,

  • method: post or put

  • success: succes message if it was success

  • id: not required but if item has id i is added to api call.

      export const useSendFormData = async ({
               formData,
               url,
               method,
               success,
               id,
             }) => {
               const [data, setData] = useState({
                 error: "",
                 loading: true,
                 success: "",
                 data: [],
               });
               const setPartData = (partialData) => setData({ ...data, ...partialData });
               try {
                 if (method === "post") {
                   const { data } = await axios.post(
                     `${SERVER_API}api/v1/${url}/${id ?? ""}`,
                     formData
                   );
                   setPartData({ data, success, error: null });
                 } else if (method === "put") {
                   const { data } = await axios.post(
                     `${SERVER_API}api/v1/${url}/${id ?? ""}`,
                     formData
                   );
                   setPartData({ data, success, error: null });
                 }
    
                 setPartData({
                   loading: false,
                 });
               } catch (err) {
                 const { data } = err.response;
                 setPartData({
                   error: data.error,
                   success: null,
                   loading: false,
                 });
               }
               return {
                 data,
               };
             };
    

    I call it inside Submit Form ,i dont know this matter but i use for handling forms react-hook-forms

     const sendFormData = useSendFormData
    
    
     const handleForm = async (info) => {
         const { data } = await sendFormData({
           formData: info,
           url: "auth/forgot-password",
           method: "post",
           success: "A password reset message has been sent to your email",
         });
    
         console.log(data);
    
         reset();
       };
    

If i change

const sendFormData = useSendFormData

to

const sendFormData = useSendFormData()

I get Cannot destructure property 'formData' of 'undefined' as it is undefined..How can i make this work and if you see any way of improving this coustom hook I would be very grateful for your help and time.

question from:https://stackoverflow.com/questions/65938455/react-invalid-hook-call-in-submitform-custom-hook-usesendformdata

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way you designed your hook the fetch is done once the hook is invoked. Instead you should define a sendFormData function inside your hook and return it along with data state (or any other variables you need). Since you want response.data to be returned I adapted the function to return response.data:

export const useSendFormData = () => {
  const [data, setData] = useState({
    error: "",
    loading: true,
    success: "",
    data: [],
  });

  const sendFormData = async ({
    formData,
    url,
    method,
    success,
    id,
  }) => {
    const setPartData = (partialData) => setData({ ...data, ...partialData });
    try {
      let response
      if (method === "post") {
        response = await axios.post(
          `${SERVER_API}api/v1/${url}/${id ?? ""}`,
          formData
        );
        setPartData({ data: response.data, success, error: null });
      } else if (method === "put") {
        response = await axios.post(
          `${SERVER_API}api/v1/${url}/${id ?? ""}`,
          formData
        );
        setPartData({ data: response.data, success, error: null });
      }
      setPartData({
        loading: false,
      });
      return response.data

    } catch (err) { 
      const { data } = err.response;
      setPartData({
        error: data.error,
        success: null,
        loading: false,
      });
      return data
    }
  }

  return {
    data, sendFormData
  };
};

With that you can call your hook properly at your component body, extracting data and sedFormData:

// here you have your data state and sendFormData extracted
const { data, sendFormData } = useSendFormData()


const handleForm = async (info) => {
  // here you have your response.data returned
  const data = await sendFormData({
    formData: info,
    url: "auth/forgot-password",
    method: "post",
    success: "A password reset message has been sent to your email",
  });

  console.log(data);

  reset();
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...