Submit Form Using React Redux - reactjs

I am using react-redux hooks.I want to dispatch an action after some validations when the form is submitted. But I cannot call usedispatch() hook outside function component. Is there any way I can dispatch an action using usedispatch() ?
My code looks as below:
import React, { Component } from 'react';
import { register } from '../../actions/auth';
import { useDispatch, useSelector } from "react-redux";
let state = {
username: '',
password1: '',
password2: '',
}
const onSubmit = (e) => {
e.preventDefault()
const dispatch = useDispatch();
if (state.password1 === state.password2) {
dispatch(register(state))
}
else {
console.log('Psw did not matched.')
}
}
const onChange = (e) => {
let field_name = e.target.name;
state[field_name] = e.target.value;
}
const Register = () => {
return (
<div className="col-md-6 m-auto">
<div className="card card-body mt-5">
<h2 className="text-center">Register</h2>
<form encType="multipart/form-data" onSubmit={onSubmit}>
<div className="form-group">
<label>Username</label>
<input
type="text"
className="form-control"
name="username"
onChange={onChange}
required/>
</div>
<div className="form-group">
<label> Password</label>
<input
type="password"
className="form-control"
name="password1"
onChange={onChange}
required/>
</div>
<div className="form-group">
<label>Confirm Password</label>
<input
type="password"
className="form-control"
name="password2"
onChange={onChange}
required/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
);
}
export default Register;
I get an error that React Hooks cannot be used outside function component and it is obvious. I am looking for a way to dispatch register action after doing some validation when form is submitted.

Since you are writing a React component, it would make sense if you define your state within and other functions within the component. This way you would be able to use hook, useDispatch as well. Also you can make your input fields controlled instead of letting them be uncontrolled
import React, { Component } from 'react';
import { register } from '../../actions/auth';
import { useDispatch, useSelector } from "react-redux";
const Register = () => {
const [state, setState] = useState({
username: '',
password1: '',
password2: '',
});
const onChange = (e) => {
let field_name = e.target.name;
let field_value = e.target.value;
setState(prev => ({...prev, [field_name]: field_value});
}
const dispatch = useDispatch();
const onSubmit = (e) => {
e.preventDefault()
if (state.password1 === state.password2) {
dispatch(register(state))
}
else {
console.log('Psw did not matched.')
}
}
return (
<div className="col-md-6 m-auto">
<div className="card card-body mt-5">
<h2 className="text-center">Register</h2>
<form encType="multipart/form-data" onSubmit={onSubmit}>
<div className="form-group">
<label>Username</label>
<input
type="text"
className="form-control"
name="username"
value={state.username}
onChange={onChange}
required/>
</div>
<div className="form-group">
<label> Password</label>
<input
type="password"
className="form-control"
name="password1"
value={state.password1}
onChange={onChange}
required/>
</div>
<div className="form-group">
<label>Confirm Password</label>
<input
type="password"
className="form-control"
name="password2"
value={state.password2}
onChange={onChange}
required/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
);
}
export default Register;

Related

useEffect not triggered on react hook form change

looking to use react hook form with useEffect to get changes in real time (as the user is filling out the form), is there a reason why useEffect isn't triggered here and if so is there a way to trigger it whenever the form data changes? example here is from https://remotestack.io/react-hook-form-set-update-form-values-with-useeffect-hook/
import React, { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
export default function SimpleForm() {
const { register, handleSubmit, reset, formState } = useForm();
const [student, initStudent] = useState(null);
useEffect(() => {
setTimeout(
() =>
initStudent({
name: "Little Johnny",
email: "lil#johnny.com",
grade: "3rd",
}),
1200
);
}, []);
useEffect(() => {
console.log("updating.,..");
reset(student);
}, [reset, student]);
function onFormSubmit(dataRes) {
console.log(dataRes);
return false;
}
return (
<div>
<h2 className="mb-3">
React Initiate Form Values in useEffect Hook Example
</h2>
{student && (
<form onSubmit={handleSubmit(onFormSubmit)}>
<div className="form-group mb-3">
<label>Name</label>
<input
type="text"
name="name"
{...register("name")}
className="form-control"
/>
</div>
<div className="form-group mb-3">
<label>Email</label>
<input
type="email"
name="email"
{...register("email")}
className="form-control"
/>
</div>
<div className="form-group mb-3">
<label>Grade</label>
<input
type="text"
name="grade"
{...register("grade")}
className="form-control"
/>
</div>
<button type="submit" className="btn btn-dark">
Send
</button>
</form>
)}
{!student && (
<div className="text-center p-3">
<span className="spinner-border spinner-border-sm align-center"></span>
</div>
)}
</div>
);
}
You can use watch mode of react hook form to get every change.
const { register, handleSubmit, reset, formState, watch } = useForm();
useEffect(() => {
watch((value, { name, type }) => console.log(value, name, type));
}, [watch]);
Read more about watch mode form here
You need to trigger a state change whenever your input field value changes, and you do so using onClick event attribute like so:
import React, { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
export default function SimpleForm() {
const { register, handleSubmit, reset, formState } = useForm();
const [student, initStudent] = useState(null);
useEffect(() => {
setTimeout(
() =>
initStudent({
name: "Little Johnny",
email: "lil#johnny.com",
grade: "3rd",
}),
1200
);
}, []);
useEffect(() => {
console.log("updating.,..");
reset(student);
}, [reset, student]);
function onFormSubmit(dataRes) {
console.log(dataRes);
return false;
}
return (
<div>
<h2 className="mb-3">
React Initiate Form Values in useEffect Hook Example
</h2>
{student && (
<form onSubmit={handleSubmit(onFormSubmit)}>
<div className="form-group mb-3">
<label>Name</label>
<input
type="text"
name="name"
{...register("name")}
onClick={(e)=>initStudent({...student, name: e.target.value})}
className="form-control"
/>
</div>
<div className="form-group mb-3">
<label>Email</label>
<input
type="email"
name="email"
{...register("email")}
onClick={(e)=>initStudent({...student, email: e.target.value})}
className="form-control"
/>
</div>
<div className="form-group mb-3">
<label>Grade</label>
<input
type="text"
name="grade"
{...register("grade")}
onClick={(e)=>initStudent({...student, grade: e.target.value})}
className="form-control"
/>
</div>
<button type="submit" className="btn btn-dark">
Send
</button>
</form>
)}
{!student && (
<div className="text-center p-3">
<span className="spinner-border spinner-border-sm align-center"></span>
</div>
)}
</div>
);
}

event.preventDefault( ) is NOT working in React

Unable to get values in console!
What am I doing it incorrectly?
Attached below is the functional component of React
The Handler Functions
import React, { useState, useRef } from 'react';
const SimpleInput = (props) => {
const nameInputRef = useRef();
const [enteredName, setEnteredName] = useState('');
const nameInputChangeHandler = (event) => {
setEnteredName(event.target.value);
};
const formSubmissionHandler = (event) => {
event.preventDefault();
console.log(enteredName);
const enteredName = nameInputRef.current.value;
console.log(enteredName);
};
return (
<form>
<div className="form-control" onSubmit={formSubmissionHandler}>
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
};
export default SimpleInput;
formSubmissionHandler should have on the form element rather than the div element.
return (
<form onSubmit={formSubmissionHandler}>
<div className="form-control">
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);

put method not working with react axios api method

I have this api running on my localhost, using drf. I defined a put method to use to update an object. When i do this in the backend it works, everything gets updated, but when i do it in the frontend nothing gets updated but i get a 200 OK status code. How can i make it work?
Here is my react code:
import React, { useState, useEffect } from 'react';
import { useHistory, useParams } from 'react-router';
import axios from 'axios';
const EkoEditPage = () => {
const [disco, setDisco] = useState("")
const [feederSource33kv, setFeederSource33kv] = useState("")
const [injectionSubstation, setInjectioSubstation] = useState("")
const [feederName, setFeederName] = useState("")
const [band, setBand ] = useState("")
const [status, setStatus] = useState("")
const history = useHistory();
const { id } = useParams();
const loadEkoMyto = async () => {
const { data } = await axios.get(`http://127.0.0.1:8000/main/view/${id}`);
setDisco(data.dicso)
setFeederSource33kv(data.feeder_source_33kv)
setInjectioSubstation(data.injection_substation)
setFeederName(data.feeder_name )
setBand(data.band)
setStatus(data.status)
}
const updateEkoMyto = async () => {
let formField = new FormData()
formField.append('disco', disco)
formField.append('feeder_source_33kv', feederSource33kv)
formField.append('injecttion_substation', injectionSubstation)
formField.append('feeder_name',feederName)
formField.append('band', band)
formField.append('status', status)
await axios({
method: 'PUT',
url: `http://127.0.0.1:8000/main/edit/${id}`,
data: formField
}).then(response => {
console.log(response.data)
})
}
useEffect (() => {
loadEkoMyto()
}, [])
return (
<div className="container">
<div className="w-75 mx-auto shadow p-5">
<h2 className="text-center mb-4">Update A Student</h2>
<div className="form-group">
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
name="disco"
value={disco}
onChange={(e) => setDisco(e.target.value)}
/>
</div>
<div className="form-group">
<input
className="form-control form-control-lg"
placeholder="Enter Your E-mail Address"
name="feeder_source_33kv"
value={feederSource33kv}
onChange={(e) => setFeederSource33kv(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your Phone Number"
name="injection_substation"
value={injectionSubstation}
onChange={(e) => setInjectioSubstation(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
placeholder="Enter Your address Name"
name="address"
value={feederName}
onChange={(e) => setFeederName(e.target.value)}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control form-control-lg"
name="address"
value={band}
onChange={(e) => setBand(e.target.value)}
/>
</div>
<select name="status" onChange={(e) => setStatus(e.target.value)}>
<option value={status}>Yes</option>
<option value={status}>No</option>
</select>
<button className="btn btn-primary btn-block" onClick={updateEkoMyto}>Update Eko</button>
</div>
</div>
);
};
export default EkoEditPage;
}

How to do routing by using Conditions in React

I am working on a React project, First I have to Signup then I stored Signup details in local storage so when I came to login screen after entering email and password and when I click submit button then it has to check the email and password from local storage. So if both are same then it should redirects to another page, I am trying to do this but it is showing some error so someone please help me to resolve this error
This is my code
This is Signup.js
import React, { useState, useRef } from 'react';
import './Signup.css';
const Signup = () => {
const [data, sendData] = useState({})
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
sendData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
localStorage.setItem('userInfo', JSON.stringify(data))
}
const myForm = useRef(null)
const resetForm = () => {
myForm.current.reset();
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='registerForm'>
<form onSubmit={handleSubmit} ref={myForm}>
<div className="form-group mb-2">
<label htmlFor="firstname">Firstname</label>
<input type="text" className="form-control" onChange={handleChange} name='firstname' id="firstname" placeholder="Enter firstname"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="lastname">Lastname</label>
<input type="text" className="form-control" onChange={handleChange} name='lastname' id="lastname" placeholder="Enter lastname"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="email">Email</label>
<input type="email" className="form-control" onChange={handleChange} name='email' id="email" placeholder="Enter email"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" onChange={handleChange} name='password' id="password" placeholder="Enter password"></input>
</div>
<button onClick={resetForm} type="submit" className="btn btn-primary mt-3">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Signup
This is Login.js
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import './Login.css';
const Login = () => {
let history = useHistory();
if (login.email && login.password === signupCredentials.email && signupCredentials.password) {
var redirect = () => {
history.push('/dashboard')
}
}
const [login, setLogin] = useState({})
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, login, { [name]: value })
setLogin(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
console.log(login)
}
const signupCredentials = JSON.parse(localStorage.getItem('userInfo'))
console.log(signupCredentials.email && signupCredentials.password)
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group mb-2">
<label htmlFor="exampleInputEmail1">Email address</label>
<input type="email" className="form-control" onChange={handleChange} name='email' id="exampleInputEmail1" placeholder="Enter email"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="exampleInputPassword1">Password</label>
<input type="password" className="form-control" onChange={handleChange} name='password' id="exampleInputPassword1" placeholder="Password"></input>
</div>
<button type="submit" onClick={redirect} className="btn btn-primary mt-3">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default Login
If you have any questions please let me know

How to store object In Cookie in React using Hooks

I am working on a React project In my project I have a scenario to store object in Cookie.
This is my code Login.js
import React, { useState } from 'react';
import './Login.css';
const Login = () => {
const [data, setData] = useState('')
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
setData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
console.log(data)
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='main'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input type="email" className="form-control" name='email' id="email" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" className="form-control" name='username' id="username" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" name='password' id="password" onChange={handleChange}></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Login
When I click submit button data will print in console. I have to store that in cookie
So what is the best way to store data object in Cookie
You can save the cookie in document.cookie. But you need to save the data as a string.
You could parse the whole object with JSON.parse, or the more elegant way is to use the specific attributes.
Cookies
But be aware that it is not save to store passwords in cookies.
Try this:
import React, { useState } from 'react';
import './Login.css';
const Login = () => {
const [data, setData] = useState('')
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
setData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
document.cookie = `email=${data.email}`;
document.cookie = `username=${data.username}`;
document.cookie = `password=${data.password}`;
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='main'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input type="email" className="form-control" name='email' id="email" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" className="form-control" name='username' id="username" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" name='password' id="password" onChange={handleChange}></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Login
You just set data to cookie:
document.cookie =
of you can use some npm lib like this:
https://www.npmjs.com/package/react-cookie

Resources