Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

react fetch post

componentDidMount() {
    // Simple POST request with a JSON body using fetch
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: 'React POST Request Example' })
    };
    fetch('https://reqres.in/api/posts', requestOptions)
        .then(response => response.json())
        .then(data => this.setState({ postId: data.id }));
}
Comment

REACT JS Rest API Fetch Post

import React, { useRef, useState } from "react";
function App() {
  const baseURL = "http://localhost:8080/api";
  const post_title = useRef(null);
  const post_description = useRef(null);
  const [postResult, setPostResult] = useState(null);

  const fortmatResponse = (res) => {
    return JSON.stringify(res, null, 2);
  }
  
  async function postData() {
    const postData = {
      title: post_title.current.value,
      description: post_description.current.value,
    };

    try {
      const res = await fetch(`${baseURL}/tutorials`, {
        method: "post",
        headers: {
          "Content-Type": "application/json",
          "x-access-token": "token-value",
        },
        body: JSON.stringify(postData),
      });

      if (!res.ok) {
        const message = `An error has occured: ${res.status} - ${res.statusText}`;
        throw new Error(message);
      }

      const data = await res.json();

      const result = {
        status: res.status + "-" + res.statusText,
        headers: {
          "Content-Type": res.headers.get("Content-Type"),
          "Content-Length": res.headers.get("Content-Length"),
        },
        data: data,
      };

      setPostResult(fortmatResponse(result));
    } catch (err) {
      setPostResult(err.message);
    }
  }
  
  const clearPostOutput = () => {
    setPostResult(null);
  }
  
  return (
    <div className="card">
      <div className="card-header">React Fetch POST - BezKoder.com</div>
      <div className="card-body">
        <div className="form-group">
          <input type="text" className="form-control" ref={post_title} placeholder="Title" />
        </div>
        <div className="form-group">
          <input type="text" className="form-control" ref={post_description} placeholder="Description" />
        </div>
        <button className="btn btn-sm btn-primary" onClick={postData}>Post Data</button>
        <button className="btn btn-sm btn-warning ml-2" onClick={clearPostOutput}>Clear</button>

        { postResult && <div className="alert alert-secondary mt-2" role="alert"><pre>{postResult}</pre></div> }
      </div>
    </div>
  );
}

export default App;
Comment

PREVIOUS NEXT
Code Example
Javascript :: passport.authenticate inside a controller 
Javascript :: jquery remove br from div 
Javascript :: nodejs command line arguments 
Javascript :: nodejs does every worker thread need a new core 
Javascript :: Appium press Enter on android with js 
Javascript :: js remove the last character of a string 
Javascript :: js update query string 
Javascript :: react native disable warnings 
Javascript :: Could not find com.yqritc:android-scalablevideoview:1.0.4 react native video 
Javascript :: js save local storage 
Javascript :: turn object into string javascript 
Javascript :: count items in div jquery 
Javascript :: on window resize react 
Javascript :: can you use javascript split with more than one separator 
Javascript :: window.onload 
Javascript :: js find lowest number in array 
Javascript :: ejs comments 
Javascript :: header ejs 
Javascript :: jquery input text value change event 
Javascript :: moment format date dd/mm/yyyy 
Javascript :: javascript disable enter key 
Javascript :: js method string remove extra spaces 
Javascript :: add select option javascript 
Javascript :: javascript count occurrences of letter in string 
Javascript :: javascript replace part of string 
Javascript :: how to remove last char from string in javascript 
Javascript :: align left text in reactstrap 
Javascript :: Javascript function to get the difference between two numbers 
Javascript :: generates a random rgb color number. 
Javascript :: momentjs number of days between two dates 
ADD CONTENT
Topic
Content
Source link
Name
8+1 =