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
USCIS Citizenship Test: Test Exemptions & Accommodations
How Newcomers to Canada Can Apply For Benefits And Tax Credits
Satyaprem Ki Katha review: Kartik Aaryan, Kiara Advani shine in this pure love story on a sensitive subject
Pinellas County Jail Mugshots 2023
East Cocalico Police Department
Western Union Mexico Rate
Wellcare Dual Align 129 (HMO D-SNP) - Hearing Aid Benefits | FreeHearingTest.org
Grange Display Calculator
Wild Smile Stapleton
The Powers Below Drop Rate
Tanger Outlets Sevierville Directory Map
2021 Tesla Model 3 Standard Range Pl electric for sale - Portland, OR - craigslist
Jscc Jweb
Raid Guides - Hardstuck
Ssefth1203
‘Accused: Guilty Or Innocent?’: A&E Delivering Up-Close Look At Lives Of Those Accused Of Brutal Crimes
Byte Delta Dental
Paradise leaked: An analysis of offshore data leaks
Classic | Cyclone RakeAmerica's #1 Lawn and Leaf Vacuum
Tygodnik Polityka - Polityka.pl
Ms Rabbit 305
Parentvue Clarkston
Milanka Kudel Telegram
Aes Salt Lake City Showdown
Hood County Buy Sell And Trade
Riversweeps Admin Login
1 Filmy4Wap In
Cpt 90677 Reimbursem*nt 2023
Kroger Feed Login
Nk 1399
Craigslist Rentals Coquille Oregon
Claio Rotisserie Menu
HP PARTSURFER - spare part search portal
Phone number detective
Sun Haven Pufferfish
Composite Function Calculator + Online Solver With Free Steps
Tamilyogi Ponniyin Selvan
Sinfuldeeds Vietnamese Rmt
To Give A Guarantee Promise Figgerits
拿到绿卡后一亩三分地
Paperless Employee/Kiewit Pay Statements
How to Quickly Detect GI Stasis in Rabbits (and what to do about it) | The Bunny Lady
Dickdrainersx Jessica Marie
Arcanis Secret Santa
The Average Amount of Calories in a Poke Bowl | Grubby's Poke
Steam Input Per Game Setting
Uncle Pete's Wheeling Wv Menu
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.