nathan111777
nathan111777

Reputation: 479

How to fix the problem of passing the value of the select to the server?

I have React app. In this app I have page with list of image categories which I get from local server and second page with posts. I also created a form that adds new post in local server. In this form I have four input : ( title, category_id, description, image).

In input category_id I write number id of category. But now I need that there was not input but there was select with titles of category, which I get from server using API method GET. And I tried to make such a select.

But my server response error:

Category_id is required

It's happening because:

How to fix this problem?


response from serever(list of categories which I get in const data):

{"data":
[{"id":20,"title":"auto"},
{"id":21,"title":"sport"},
{"id":23,"title":"new"}
]}

AddPost.js:

const AddPost = () => {

      const formRef = useRef();
      const [category, setCategory] = useState('');          // <-- category which I select in select will fall here
      const [categories, setCategories] = useState([]);      // <-- a list of existing categories will fall here
  
      useEffect(() => {
           fetchData(); 
      }, []);
    
    async function fetchData() {                                    // <-- get List of categories
        const data = await api(`${listRoute}`, {  method: 'GET'});
        setCategories(data.data.map(item => item.title));          // <-- now I set title of category in select
    }

   const handleSubmit = async (event) => {                // <-- send form to local server
       const data = new FormData(formRef.current);        // <-- value from my from will fall here 
       event.preventDefault();
              const response = await apiImage(`${imageRoute}`, {
                 method: 'POST',
                 body: data,    
              });};
    
   const upadateSelectCategory = e => {       // <-- choose category in select in form
        setCategory(e.target.value);
   };
      
   return (  
    <div>
        <form onSubmit={handleSubmit} ref={formRef}>
          <input type="text" name="title"/>
          <input type="text" name="description"/>
          <input type="file" name="image" accept="image/*"/>
        /*<input type="text" name="category_id"/>*/      // <-- Instead this input now I write SelectCategory:
          <SelectCategory upadateSelectCategory={upadateSelectCategory} categories={categories} value={category} />
          
          <button type="submit">Add</button>
      </form>
   </div>
   );
};

SelectCategory.js:

export default (props) => {
    return (
      <div>
        <select onChange={props.upadateSelectCategory} value={props.value}>
          <option value="">-- Category --</option>
          {props.categories.map(item => <option key={item}>{item}</option>)}  
        </select> 
      </div>
  );}

Upvotes: 0

Views: 128

Answers (1)

BeHappy
BeHappy

Reputation: 3978

You have to send category_id and what now you are store is only title.

You have to store id, too.

async function fetchData() {
  const data = await api(`${listRoute}`, {  method: 'GET'});
  setCategories(data.data); // Change here
}

and In your SelectCategory component:

export default (props) => {
    return (
      <div>
        <select onChange={props.upadateSelectCategory} value={props.value}>
          <option value="">-- Category --</option>
          {props.categories.map(item => <option value={item.id} key={item.id}>{item.title}</option>)}  
        </select> 
      </div>
  );}

here set category_id as value of option.

and in handleSubmit add this code after const data = new FormData(formRef.current);:

data.append('category_id', category)

Upvotes: 2

Related Questions