React自定义钩子未提供POST请求的结果。

huangapple go评论69阅读模式
英文:

React custom hook does not give result of POST

问题

以下是您要翻译的内容:

The custom hook post method working fine at the same time the response adding state taking time.

console.log(jsonResult)

shows the response of POST method at the same time responseData shows null

usePostQuery

import { useCallback, useState } from "react";

interface bodyData {
  message: string,
  author: string
}

const usePostQuery = (url: string, data?: bodyData ) => {
  const [responseData, setResponseData] = useState();
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState('');

  const callPost = useCallback( async (data: bodyData) => {
      try {
        setLoading(true);

        const response = await fetch(url, {
          method: "POST",
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            title: data.message,
            userId: 15
          })
        });

        const jsonResult = await response.json();
        console.log('--------jsonResult---------');
        console.log(jsonResult)

        setResponseData(jsonResult);
      } catch (error: any) {
        setError(error.message);
      } finally {
        setLoading(false);
      }
    },
    [url]
  );

  return { responseData, loading, error, callPost };
};

export default usePostQuery;
const { responseData, loading, error, callPost } = usePostQuery('https://jsonplaceholder.typicode.com/posts')

The responseData is not giving post call response

  useEffect(() => {
    if (draftMessage && myMessage) {
      // submitNewMessage()
      console.log("post my message to server");
      callPost({
        message: myMessage,
        author: "Mo"
      });
      if (loading === false) {
        setMyMessage("");
        setdraftMessage(false);
        console.log("after ", responseData);
      }
      console.log("responseData ", responseData);
    }
  }, [draftMessage, myMessage]);

The fetch is successful because the console in side fetch response shows the API response.

英文:

The custome hook post method working fine at the same time the response adding state taking time.

console.log(jsonResult)

shows the response of POST method at the same time responseData shows null

usePostQuery

import { useCallback, useState } from &quot;react&quot;;

interface bodyData {
  message: string,
  author: string
}

const usePostQuery = (url: string, data?: bodyData )=&gt; {
  const [responseData, setResponseData] = useState();
  const [loading, setLoading] = useState&lt;boolean&gt;(false);
  const [error, setError] = useState(&#39;&#39;);

  const callPost = useCallback( async (data: bodyData) =&gt; {
      try {
        setLoading(true);

        const response = await fetch(url, {
          method: &quot;POST&quot;,
          headers: {
            &#39;Content-Type&#39;: &#39;application/json&#39;
          },
          body: JSON.stringify({
            title: data.message,
            userId: 15
          })
        });

        const jsonResult = await response.json();
        console.log(&#39;--------jsonResult---------&#39;);
        console.log(jsonResult)

        setResponseData(jsonResult);
      } catch (error: any) {
        setError(error.message);
      } finally {
        setLoading(false);
      }
    },
    
); return { responseData, loading, error, callPost }; }; export default usePostQuery;

React自定义钩子未提供POST请求的结果。

const { responseData, loading, error, callPost } = usePostQuery(&#39;https://jsonplaceholder.typicode.com/posts&#39;)

The responseData is not giving post call response

  useEffect(() =&gt; {
    if (draftMessage &amp;&amp; myMessage) {
      // submitNewMessage()
      console.log(&quot;post my message to server&quot;);
      callPost({
        message: myMessage,
        author: &quot;Mo&quot;
      });
      if (loading === false) {
        setMyMessage(&quot;&quot;);
        setdraftMessage(false);
        console.log(&quot;after &quot;, responseData);
      }
      console.log(&quot;responseData &quot;, responseData);
    }
  }, [draftMessage, myMessage]);

The fetch is successful because the console in side fetch response shows the API response.

答案1

得分: 1

你的自定义钩子没有问题。问题出在你的 effect 钩子中。

它只在它的依赖项更改时触发,即 draftMessagemyMessage。它不会重新评估 loadingresponseData,因此只会在触发时看到它们的状态。

不太清楚你是如何使用 draftMessage 状态的。相反,我建议在你的提交处理程序中简单地触发 callPost...

export default function App() {
  const [myMessage, setMyMessage] = useState("");

  const { responseData, loading, callPost } = usePostQuery(
    "https://jsonplaceholder.typicode.com/posts"
  );

  const handleMyMessage = (val) => {
    setMyMessage(val);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    await callPost({ message: myMessage, author: "Mo" });
    setMyMessage("");
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {loading ? (
        <p>Loading...</p>
      ) : (
        <ChatForm
          onChange={handleMyMessage}
          myMessage={myMessage}
          handleSubmit={handleSubmit}
        />
      )}
      <pre>responseData = {JSON.stringify(responseData, null, 2)}</pre>
    </div>
  );
}

你的钩子控制了 loadingresponseData 状态,所以你的组件真的没有太多事情要做。

英文:

There's nothing wrong with your custom hook. The issue is in your effect hook.

It only triggers when its dependencies change, ie draftMessage and myMessage. It does not re-evaluate loading or responseData so will only ever see their states at the time it is triggered.

It's really unclear what you're using the draftMessage state for. Instead, I would simply trigger the callPost in your submit handler...

export default function App() {
  const [myMessage, setMyMessage] = useState(&quot;&quot;);

  const { responseData, loading, callPost } = usePostQuery(
    &quot;https://jsonplaceholder.typicode.com/posts&quot;
  );

  const handleMyMessage = (val) =&gt; {
    setMyMessage(val);
  };

  const handleSubmit = async (event) =&gt; {
    event.preventDefault();
    await callPost({ message: myMessage, author: &quot;Mo&quot; });
    setMyMessage(&quot;&quot;);
  };

  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;h1&gt;Hello CodeSandbox&lt;/h1&gt;
      &lt;h2&gt;Start editing to see some magic happen!&lt;/h2&gt;
      {loading ? (
        &lt;p&gt;Loading...&lt;/p&gt;
      ) : (
        &lt;ChatForm
          onChange={handleMyMessage}
          myMessage={myMessage}
          handleSubmit={handleSubmit}
        /&gt;
      )}
      &lt;pre&gt;responseData = {JSON.stringify(responseData, null, 2)}&lt;/pre&gt;
    &lt;/div&gt;
  );
}

React自定义钩子未提供POST请求的结果。

Your hook controls the loading and responseData states so there's really very little for your components to do.

huangapple
  • 本文由 发表于 2023年1月9日 10:22:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75052660.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定