Sending to API in React.js (2024)

In the previous step, we managed to fetch data from the server and display the collection of tasks on the client in our React.js application. Let's do the opposite: when users add a new task via the form, we need to send it to the server and eventually persist in the database. We will be using the same endpoint in our API, i.e. /_api/task. The only difference is the type of invoked action, i.e. instead of doing a GET request, we will send a POST request along with the payload containing the new task to add.

As for data fetching, we will use the react-query library to also send data out. Since the intention is to change the server data (we want to append a new task to the collection), we need to define a mutation via the useMutation hook. Similarly to useQuery, this hook takes as input a request function that defines the logic for sending new task to the server. Contrary to previous example, this time we need to send a POST request, i.e. we want to send what the user entered in the input field to the server-side API. Our data is a Task record containing just name. Also, since we send it as the application/json content type, we must stringify the payload before passing it as the body of the request.

import React from 'react';import { useForm } from "react-hook-form";

import { useMutation } from "react-query";

import { Task } from '@/types';

const request = (data: Task) =>

fetch('/_api/task', {

method: 'POST',

headers: {

'Content-Type': 'application/json'

},

body: JSON.stringify(data),

})

export const TaskInput: React.FC<{}> = () => { const { register, handleSubmit, errors } = useForm();

const mutation = useMutation(request);

const onSubmit = handleSubmit(data => mutation.mutate(data));

return ( <div> <form onSubmit={onSubmit}> <input name="name" ref={register({ required: true })} placeholder="Add new item..." type="text" /> <button type="submit">Add</button> </form> <div>{errors.name && <span>This field is required</span>}</div> </div> );}
Sending to API in React.js (2024)
Top Articles
They purchased homes right before the real estate downturn. Now, they're struggling to close
How Do You Refinance a Home Equity Loan?
Nambe Flatware Discontinued
Lpga Scores Espn
Irrationale Kitchen
Bridgeport Transit Bus Schedule
Pa Speedtest Rcn Merlin
Wow Pickaxe Blade
Jug Cousin Crossword Clue
Daisy Maldonado Muckrack
Lyneer Staffing Solutions Lyndhurst Nj
ZQuiet Anti-Snoring Mouthpiece Review 2024 - Sleep Doctor
Cars & Trucks - By Owner near Kissimmee, FL - craigslist
Ds Cuts Saugus
Homepoint Financial Wholesale Login
Train Parade Float Ideas
Herriman Heights Dental
Mail Healthcare Uiowa
Uw Madison Mechanical Engineering Flowchart
Whisk Recipe Calculator
Mte Outage Map
Paperlesspay Talx Ingram
Crary Realty Grand Forks Nd
Find A Red Cross Blood Drive
Vystar Cars For Sale
Wrj Mugshots
Doculivery Trinity Health
R/Sandiego
Devotion Showtimes Near Xscape Theatres Blankenbaker 16
Shaanxi Y-9 Medium-Lift Transport Aircraft
Craigslist Malone New York
Craigslist Hunting Land For Lease In Ga
Craigslist Rentals Coquille Oregon
Slv Fed Routing Number
Osrs Bowfa Max Hit
Craigslist Pets Salina Ks
Wild West Western Wear Surfside Beach Photos
Mangmirror
Lake George Ny Craigslist
Atrium Orthopedic Urgent Care
When His Eyes Opened Chapter 3096
Finalcon 2022
Infinite Campus Farmingdale
Sierra At Tahoe Season Pass Costco
Cherry Crush Webtoon Summary
Frequently Asked Questions
Tucker Gott Jaclyn Weiss
Ter Review
Judy Joo Husband David Allen
0Gomovies: Free Malayalam, Tamil & Hindi Movies - UK Journal
Espn Sirius Radio Schedule
Craigslist Domestic Job
Latest Posts
Article information

Author: Fr. Dewey Fisher

Last Updated:

Views: 6112

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Fr. Dewey Fisher

Birthday: 1993-03-26

Address: 917 Hyun Views, Rogahnmouth, KY 91013-8827

Phone: +5938540192553

Job: Administration Developer

Hobby: Embroidery, Horseback riding, Juggling, Urban exploration, Skiing, Cycling, Handball

Introduction: My name is Fr. Dewey Fisher, I am a powerful, open, faithful, combative, spotless, faithful, fair person who loves writing and wants to share my knowledge and understanding with you.