0
votes

I want to POST to a login form using React JSX and JWT API auth already installed. I don't want to use axios post, instead I want to use the hooks method useState, useEffect with async/await and onFormSubmit function. How do I POST the data values username and password between the state and effect. thanks

const [login, setLogin] = useState({
    username: '',
    password: '',
    userNiceName: '',
    userEmail: '',
    loggedIn: false,
    loading: false,
    error: ''
})


useEffect(() => {

}, [])

const postData = async () => {
    const response = await fetch('http://localhost:8888/react/wp-json/jwt-auth/v1/token', requestOptions )
    const login = await response.json()
    const requestOptions = {
            method: 'POST',
           headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
    }


const onFormSubmit = e => {
    e.preventDefault()
    const data = {
        username: e.target[0].value,
        password: e.target[2].value,
    }
1
useEffect is for use of code that should run every time your component updates, a replacement for componentDidMount and componentDidUpdate. It looks like you should just be using an onSubmit event callback (which is still how events are handled even with react hooks). This page may help you: reactjs.org/docs/forms.html .yeerk

1 Answers

1
votes
const [login, setLogin] = useState({
    username: '',
    password: '',
})
    

const [logindata, setLogindata] = useState({
    userNiceName: '',
    userEmail: '',
    loggedIn: false,
    loading: false,
    error: ''
})


useEffect(() => {
    postData()
    return ()=>{}
    }, [login])
    
    const postData = async () => {
    
    const requestOptions = {
                    method: 'POST',
                   headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(login)
            }
        const response = await fetch('http://localhost:8888/react/wp-json/jwt-auth/v1/token', requestOptions )
        const loginresp = await response.json()
    setLogindata({...logindata, ...loginresp})
    }
       
    
    
    const onFormSubmit = e => {
        e.preventDefault()
        const data = {
            username: e.target[0].value,
            password: e.target[2].value,
        }
        setLogin({...login,...data})
    }