Ask Your Question
0

How can I send a POST with React after my website has loaded?

asked 2021-09-15 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-05-11 09:00:00 +0000

plato gravatar image

You can use the fetch() function to make a POST request after your React website has loaded. Here's an example:

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    fetch('https://example.com/api/submit', {
      method: 'POST',
      body: JSON.stringify({ name: 'John', age: 30 }),
      headers: { 'Content-Type': 'application/json' }
    })
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error(error));
  }, []);

  return <h1>Hello World!</h1>;
}

In this example, the useEffect hook is used to make the POST request when the component is mounted. The empty array [] passed as the second argument ensures that the effect is only run once, when the component mounts. The fetch function is used to make the POST request, and the data to be sent is provided as the body option. The headers option is used to specify that the data is in JSON format. Finally, the response is parsed as JSON and logged to the console.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-15 11:00:00 +0000

Seen: 12 times

Last updated: May 11 '21