Home > database >  Input values in state as route params
Input values in state as route params

Time:12-01

I want to send input values as route params to server. Should I write a function to encode values? I'm trying to do this without any libraries..

By coincidence, I mistyped localhost 8000,then the browser appended localhost 3000 url to 8000 and only then did the set Search Params work and I did get the values appended to as route params but the url of server wasn't right one, obviously. Here 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;

On Submitting I only get empty object URLSearchParams{}

CodePudding user response:

The setSearchParams function works like the navigate function in that it effects a navigation action but only updates the current URL's search string. The code isn't actually updating the searchParams variable.

You want to take 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);
};
  • Related