skip to Main Content
<select className="form-control"
    placeholder="Category name"
    name="category"
    value={course.category}
    onChange={handleChange}>
    {categories.map((category) => <option key={category._id} data-id={category._id}>{category.categoryName}</option>)}
</select>

Setting default value:

const handleCourseSubmit = async e => {
    e.preventDefault()
    setCourse((prevState) => {
        return { ...prevState, category: categories[0].categoryName }
    })
    console.log('create.js:: handleCourseSubmit:: data: ', course.category); //prints empty string created from initial state
}

How do I set default value on submit?

2

Answers


  1. You can use the useEffect hook.

    const handleCourseSubmit = async e => {
        e.preventDefault();
        setCourse(prevState => {
            return { ...prevState, category: categories[0].categoryName };
        });
    }
    useEffect(() => {
        console.log('create.js:: Updated category: ', course.category);
    }, [course.category]);
    
    Login or Signup to reply.
  2. import React, { useState, useEffect } from 'react';
    
    function YourComponent() {
        const [course, setCourse] = useState({
            category: '', // Initial category value
            // ... other state properties
        });
    
        useEffect(() => {
            console.log('Updated category:', course.category);
        }, [course.category]);
    
        const handleChange = (e) => {
            // Handle change logic here
        };
    
        const handleCourseSubmit = async (e) => {
            e.preventDefault();
            setCourse((prevState) => {
                return { ...prevState, category: categories[0].categoryName };
            });
        };
    
        // Render your component
    }
    
        Logging inside the callback function:
    
    const handleCourseSubmit = async (e) => {
        e.preventDefault();
        setCourse((prevState) => {
            console.log('Updated category:', prevState.category);
            return { ...prevState, category: categories[0].categoryName };
        });
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search