0

I am trying to send the state object of my component. I was using a class component and converted it to a function utilising useState() but now I can't access the state object using this.state.

I have substituted it by creating an object called state but I am guessing this isnt the most elegant solution...

export default function Contact () {
    const [name, setName] = useState("")
    const [email, setEmail] = useState("")
    const [enquiryType, setEnquiryType] = useState("General Enquiry")
    const [message, setMessage] = useState("")

    const state = {
        name,
        email,
        enquiryType,
        message
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        console.log(state) // vs this.state
        var service_id = "default_service";
        var template_id = "message_template";
        var user_id = "user_[whatever]"
        emailjs.send(service_id, template_id, state, user_id); // vs this.state
    }

}

atman_lens
  • 474
  • 2
  • 6
  • 16

2 Answers2

0

You've broke down your state into 4 different states. You can use these states separately as well but I'd recommend you to study useReducer hook if you want to merge these states into 1 object. You can read Kent C. dodds post for comparison.

Muhammad Ali
  • 2,538
  • 2
  • 16
  • 21
0

if I followed your issue properly, you can use useReducer or if you want to use useState, you can try this method:

const initialStates={...yourObject}
const [state,setState]=useState(initialStates)

and then pass it as state

RamTn
  • 99
  • 5