javascript - How to update the state after a data update through an API request in React? - Stack Overflow

I have a small problem. I have this fetch data in one ponent which is working perfectly:const [item, s

I have a small problem. I have this fetch data in one ponent which is working perfectly:

const [item, setItem] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch("https://api/products")
      .then((response) => response.json())
      .then((data) => setItem(data))
      .finally(() => setLoading(false));
  }, []);

Then I have this POST in a different ponent:

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await fetch("https://api/products", {
        method: "POST",
        headers: { admin: "true", "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
    } catch (error) {
      console.log("error");
    }
  };

How can I get the new data of the first ponent after using POST without reloading the web page?

I have a small problem. I have this fetch data in one ponent which is working perfectly:

const [item, setItem] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch("https://api/products")
      .then((response) => response.json())
      .then((data) => setItem(data))
      .finally(() => setLoading(false));
  }, []);

Then I have this POST in a different ponent:

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await fetch("https://api/products", {
        method: "POST",
        headers: { admin: "true", "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
    } catch (error) {
      console.log("error");
    }
  };

How can I get the new data of the first ponent after using POST without reloading the web page?

Share Improve this question edited Apr 30, 2023 at 9:01 Youssouf Oumar 46.6k16 gold badges103 silver badges105 bronze badges asked Jun 23, 2022 at 6:07 Javier PérezJavier Pérez 1511 silver badge8 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 4

You need to be able to append that new data, body inside item array, means you need to call this setItem(prev => [...prev, body]) in your try-catch, something like:

const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await fetch("https://api/products", {
        method: "POST",
        headers: { admin: "true", "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      setItem(prev => [...prev, body]); // here you add the new data
    } catch (error) {
      console.log("error");
    }
  };

Now how you would access this setItem function? Well if the ponent that's making the POST request is a child of the ponent where you have this line const [item, setItem] = useState([]), you could pass setItem as a props.

If it's not the case, either you move this const [item, setItem] = useState([]) inside a ponent that's parent of all those ponents and pass down what you need as props or use a state management solution like the context API.

You must call the function again when response is true. I mean your function when getting data.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745381492a4625247.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信