Search code examples
reactjsformsreduxreact-reduxfetch

How to submit a form with react and redux?


I am trying to submit a POST form with a simple html form and I also use redux with a userAction which allows to store the user and the token returned by the express js API, but the submission does not work, when I submit the form, nothing happens I can't even get into the fetch function of the action.

import '../styles/ConnexionModal.css';
import { userLogin } from '../redux/userActions';
import { useState } from 'react';
// import { useSelector } from 'react-redux';

const ConnexionModal = ({ showModal, hideModal }) => {
    
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    // const message = useSelector(state => state.userReducer.message);
    // console.log(message);

    const handleChangeEmail = (event) => {
        setEmail(event.target.value);
    }

    const handleChangePassword = (event) => {
        setPassword(event.target.value);
    }

    const handleSubmit = (e) => {
        e.preventDefault();
        userLogin(email, password);
    }

    return (
        showModal && ( 
        <div className="modalBg">
            <div className="modalContainer">
                <div className="modalHeader">
                    <h1 className="modalTitle">Connexion</h1>
                </div>
                <div className="modalBody">
                    <form method="POST" onSubmit={handleSubmit}>
                        <div className="formGroup">
                            <label htmlFor="email" className="info">Email</label>
                            <input className="field" name="email" id="email" type="email" value={email} onChange={handleChangeEmail} autoFocus required />
                        </div>
                        <div className="formGroup">
                            <label htmlFor="password" className="info">Mot de passe</label>
                            <input className="field" name="password" id="password" type="password" value={password} onChange={handleChangePassword} required />
                        </div>
                        <div className="formGroup">
                            <label htmlFor="connexion" className="submitButton">Se connecter</label>
                            <input className="field submit" id="connexion" name="submit" type="submit" />
                        </div>
                    </form>
                </div>
                <div className="close">
                    <button onClick={() => hideModal()} className="closeButton">Fermer</button>
                </div>
            </div>
        </div>
        )
    )

}

export default ConnexionModal;

export const LOGIN = "LOGIN";
export const ERROR = "ERROR";

export const userLogin = (email, password) => {

    return async dispatch => {
        
        console.log('test');
        fetch('http://192.168.1.36:4000/api/users/login', {
            method: "POST",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                email: email,
                password: password
            })
        })
        .then((res) => res.json())
        .then(async (res) => {
            if(!res.error) {
                localStorage.setItem('auth', res.token);
                dispatch({ type: LOGIN, user: res.user, token: res.token });
            } else {
                dispatch({ type: ERROR, message: res.error });
            }
        })

    }

}

The console.log ('test') does not display anything which means I am not even accessing the userLogin function in my component.


Solution

  • I assume you are also using redux-thunk.

    You should always pass the action inside your container to a redux dispatch function. E.g.

    import '../styles/ConnexionModal.css';
    import { userLogin } from '../redux/userActions';
    import { useState } from 'react';
    import { useDispatch } from 'react-redux';
    
    const ConnexionModal = ({ showModal, hideModal }) => {
        const dispatch = useDispatch();
        const [email, setEmail] = useState('');
        const [password, setPassword] = useState('');
    
        const handleChangeEmail = (event) => {
            setEmail(event.target.value);
        }
    
        const handleChangePassword = (event) => {
            setPassword(event.target.value);
        }
    
        const handleSubmit = (e) => {
            e.preventDefault();
            dispatch(userLogin(email, password));
        }
    
        ...