I want to send the entered value to the server as a routing parameter. Should I write a function to encode these values? I'm trying to accomplish this without any libraries.
Coincidentally, I entered localhost 8000 by mistake, and then the browser appended the URL for localhost 3000 to 8000 before I could use set Search Params, and I did append those values to the route parameters, but the server's URL Obviously incorrect.
This is my code:
import axios from 'axios'; import React, { useState } from 'react'; import { useSearchParams } from 'react-router-dom'; const AddProductForm = ({ id }) => { let [searchParams, setSearchParams] = useSearchParams(); const [input, setInput] = useState({ title: '', price: '', rating: '', description: '', }); const handleSubmit = (e) => { e.preventDefault(); setSearchParams(input) axios .put(`http://localhost:8080/api/v1/products/${id}?` + searchParams) .then((res) => console.log(res)) .catch((err) => console.log(err)); }; const onChange = (e) => { //function to handle change of each input } return ( <div className='container' > <form className='form' onSubmit={handleSubmit}> <div className='form_inputs'> <h1>Edit Product</h1> <div className='flex-column'> <label>Add new title</label> <input type='text' value={input.title} onChange={onChange} name='title' placeholder='Title' /> </div> <div className='flex-column'> <label>Add new price</label> <input type='number' value={input.price} onChange={onChange} name='price' placeholder='Price' /> </div> //All other inputs <button className='btn-block' type='submit'> Create </button> </form> </div> ); }; export default AddProductForm;
When submitting, I only get the empty object URLSearchParams{}
P粉8271215582023-09-12 13:29:21
Function setSearchParams
works like function navigate
, it performs navigation operations but only updates the search string for the current URL. The code doesn't actually update the searchParams
variable.
You want to get the input
state and create a new URLSearchParams
object.
Example:
const handleSubmit = (e) => { e.preventDefault(); const searchParams = new URLSearchParams(input); axios .put(`http://localhost:8080/api/v1/products/${id}?${searchParams.toString()}`) .then(console.log) .catch(console.warn); };