How to POST request using axios with React Hooks? - reactjs

This is my Signupcomponent
const SignupComponent = () => {
const [values, setValues] = useState({
username: 'silvio1',
name: 'Silvioo',
email: 'berlusconi#gmail.com',
password: '123ooo007',
});
const [loading, setLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
const { username, name, email, password } = values;
const user = {username, name, email, password};
await axios.post('${API)/signup', user);
};
const handleChange = name => e => {
setValues({ ...values, [name]: e.target.value });
};
const showLoading = () => (loading ? <div className="alert alert-info">Loading...</div> : '');
const signupForm = () => {
return (
<form onSubmit={handleSubmit}>
<div className="form-group">
<input
value={values.username}
onChange={handleChange('username')}
type="text"
className="form-control"
placeholder="Type your username"
/>
</div>
<div className="form-group">
<input
value={values.name}
onChange={handleChange('name')}
type="text"
className="form-control"
placeholder="Type your name"
/>
</div>
<div className="form-group">
<input
value={values.email}
onChange={handleChange('email')}
type="email"
className="form-control"
placeholder="Type your email"
/>
</div>
<div className="form-group">
<input
value={values.password}
onChange={handleChange('password')}
type="password"
className="form-control"
placeholder="Type your password"
/>
</div>
<div>
<button className="btn btn-primary">Signup</button>
</div>
</form>
);
};
return <React.Fragment>
{showLoading()}
{signupForm()}
</React.Fragment>;
};
export default SignupComponent;
EDIT
I changed my code(zhulien's accepted answer).
Signup page appears,I try to sign up user.
I got error
Unhandled Runtime Error
Error: Request failed with status code 404
Call Stack
createError
node_modules/axios/lib/core/createError.js (16:0)
settle
node_modules/axios/lib/core/settle.js (17:0)
XMLHttpRequest.handleLoad
node_modules/axios/lib/adapters/xhr.js (62:0)
Frontend folder
components
config.js
next.config.js
node_modules
package.json
package-lock.json
pages
My pages folder
_document.js
index.js
signin.js
signup.js
signup.js imports the code above
import Link from 'next/link';
import Layout from '../components/Layout';
import SignupComponent from '../components/frontauth/SignupComponent';
const Signup = () => {
return (
<Layout>
<h2>Signup page</h2>
<SignupComponent />
</Layout>
);
};
My next.config.js
{
APP_NAME: 'BLOG FRONTEND',
APP_DEVELOPMENT: 'http://localhost:3000',
PRODUCTION: false
}
And config.js
const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig);
export const API = publicRuntimeConfig.PRODUCTION
? 'https://cryptoblog.com'
: 'http://localhost:3000';
export const APP_NAME = publicRuntimeConfig.APP_NAME;
I am new to React and React Hooks. How to solve this problem?

First of all, you're trying to access {username}(which doesn't exist) instead of the state property which is values.username. Furthermore, don't use hooks in event handlers, they should be used in the top level body of the component or in custom hooks only. Checkout this: React hooks rules.
So:
In your form you have to use the state(values) properties.
Extract useEffect hook in the main body flow of the component or BETTER remove it altogether as you're not using it properly currently. You're better of with just the simple event handler for form submit which should post the data somewhere without setting any state.
Your code could look something like:
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { API } from '../../config';
const SignupComponent = () => {
const [values, setValues] = useState({
username: 'silvio1',
name: 'Silvioo',
email: 'berlusconi#gmail.com',
password: '123ooo007',
});
const [loading, setLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
const { username, name, email, password } = values;
const user = {username, name, email, password};
await axios.post('${API)/signup', user);
};
const handleChange = name => e => {
setValues({ ...values, [name]: e.target.value });
};
const showLoading = () => (loading ? <div className="alert alert-info">Loading...</div> : '');
const signupForm = () => {
return (
<form onSubmit={handleSubmit}>
<div className="form-group">
<input
value={values.username}
onChange={handleChange('username')}
type="text"
className="form-control"
placeholder="Type your username"
/>
</div>

this is how it should be:
useEffect(() => {
postUser();
}, []);
not inside the function the way you have done it:
const handleSubmit = e => {
e.preventDefault();
setValues({...values});
const { username, name, email, password } = values;
const user = {username, name, email, password};
async function postUser () {
const result = await axios.post('${API)/signup', user);
};
useEffect(() => {
postUser();
}, []);
};
UseEffects aren't meant to be placed inside your functions.Just place them inside your functional component,with some value(or no value) inside your dependency array of the useEffect.These values present inside the array will trigger the useEffect whenever they get changed.

Related

react page is rendering blank [duplicate]

This question already exists:
return not displaying page data react functional component
Closed 1 year ago.
I have this, my entire react page:
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useHistory } from "react-router-dom";
import { useMemo } from "react";
import { connect } from "react-redux";
import AdminNav from "../../../components/admin/AdminNav"
import AdminAboutUsNav from "../../../components/admin/AdminAboutUsNav"
import Header from "../../../components/app/Header";
import { setNavTabValue } from '../../../store/actions/navTab';
import { makeStyles, withStyles } from "#material-ui/core/styles";
import "../../../styles/AddMembershipPage.css";
const AddMembershipPage = (props) => {
const history = useHistory();
const [myData, setMyData] = useState({});
let ssoDetails = {
name: props.blue.preferredFirstName + " " + props.preferredLastName,
email: props.blue.preferredIdentity,
cnum: props.blue.uid,
empType: "part-time"
}
this.state = {
cnum: ssoDetails.cnum,
empType: ssoDetails.empType,
email: ssoDetails.email,
name: ssoDetails.name,
phone: "",
// building: building,
siteList: "",
status: ""
};
const handleInputChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
var date = Date().toLocaleString();
const { cnum, empType, email, name, phone, siteList, status } = this.state;
const selections = {
cnum: cnum,
empType: empType,
email: email,
name: name,
phone: phone,
// building: building,
siteList: siteList,
status: status
};
axios
.post("/newMembership", selections)
.then(
() => console.log("updating", selections),
(window.location = "/admin/services")
)
.catch(function (error) {
// alert(error)
window.location = "/admin/services/new";
});
};
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
backgroundColor: theme.palette.background.paper,
},
}));
const classes = useStyles();
return (
<div className={classes.root}>
<AdminNav />
{/* <Header title="Services - Admin" /> */}
{/* <AdminAboutUsNav /> */}
<div className="App">
<form onSubmit={this.handleSubmit}>
<h1>Join Us!</h1>
<input value={ssoDetails.name} readOnly name="name" onChange={this.handleInputChange}></input>
<input type="email" value={ssoDetails.email} readOnly name="email" onChange={this.handleInputChange}></input>
<input type="hidden" value={ssoDetails.cnum} readOnly name="cnum" onChange={this.handleInputChange}></input>
<input type="text" value={ssoDetails.empType} readOnly name="empType" onChange={this.handleInputChange}></input>
<input type="text" placeholder="Phone Number" name="phone" onChange={this.handleInputChange}></input>
<input type="text" placeholder="Site List" name="siteList" onChange={this.handleInputChange}></input>
{/* <input type="password" placeholder="Password"></input> */}
<button type="submit">Register</button>
</form>
</div>
</div>
);
}
const mapStateToProps = (state) => {
return {
siteTab: state.siteTab,
blue: state.blue
}
}
const mapDispatchToProps = (dispatch, props) => ({
setNavTabValue: (value) => dispatch(setNavTabValue(value))
});
export default connect(mapStateToProps, mapDispatchToProps)(AddMembershipPage);
however, when I try to run this page, it just shows up blank. It started doing this after I added const handleInputChange, and const handleSubmit to the code. I am basically just trying to submit a form, and it is more complex then I imagined. Before I added those 2 things I just mentioned, the page was working perfectly. but now, I cannot figure it out, and really could use some guidance/help to try to fix this up. any ideas?
It's function component so you don't need to call with this.handleSubmit
Just change it to the onSubmit={handleSubmit}> and onChange={handleInputChange}>
Also remove this.state and use useState instead because this.state was available in class based component not in the function component.

Got Received number of calls: 0 error for login functionality

I am writing unit test case for login.
I am unsure about how to test handle submit as it contains one of the service call in the form of getToken() method, it would be greate if someone can guide me through how to handle this situation.
export const getToken = (credentials) => {
const token = 'abccss';
if (
credentials.username === 'test#test.com' &&
credentials.password === '123'
) {
return token;
} else {
return null;
}
};
The above code fetches user name and password and sends it to login in handleSubmit() function
//all imports(loginservice,auth etc etc)
import './Login.scss';
const Login = () => {
const [email, setEmail] = useState('');
const [pwd, setPwd] = useState('');
const authCon = useContext(AuthContext);
const handleSubmit = (e) => {
e.preventDefault();
const token = getToken({ username: email, password: pwd });
if (token) {
authCon.login(token);
window.location.href = '/dashboard';
}
};
return (
<div className="div-login">
<div className="div-login-logo">
<img src={logo} alt="Logo"></img>
</div>
<div>
<form onSubmit={handleSubmit}>
<input
className="credentials-input"
type="email"
value={email}
placeholder="Email Address"
required
onChange={(e) => setEmail(e.target.value)}
/>
<input
className="credentials-input"
type="password"
value={pwd}
placeholder="Password"
required
onChange={(e) => setPwd(e.target.value)}
/>
<button className="login-button" type="submit">
Log In
</button>
</form>
</div>
</div>
);
};
export default Login;
Test Code
test('Submit shoud work successfully', () => {
const mockLogin = jest.fn();
const { getByRole } = render(<Login handleSubmit={mockLogin} />);
const login_button = getByRole('button');
fireEvent.submit(login_button);
expect(mockLogin).toHaveBeenCalledTimes(1);
});
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
As I am new to React, help will be appreciated.
The actual issue is handleSubmit is not a props of Login component.
Also you can't test the internal methods of a component using React testing Library, you have to move the handleSubmit method to either parent component or a common file and pass it to the login component or import it so that you can mock the method and perform the test.
Move the getToken and handleSubmit to a common file like below,
common.ts
export const getToken = (credentials:any) => {
const token = 'abccss';
if (
credentials.username === 'test#test.com' &&
credentials.password === '123'
) {
return token;
} else {
return null;
}
};
export const handleSubmit = (e:any, email:string, pwd: string) => {
e.preventDefault();
const token = getToken({ username: email, password: pwd });
if (token) {
// authCon.login(token);
window.location.href = '/dashboard';
}
};
Modify Login.ts as like below ( see below handleSubmit is not internal and its imported from common.ts file so we that we can mock it)
import React, { useContext, useState } from 'react';
import { getToken, handleSubmit } from './common';
const Login = () => {
const [email, setEmail] = useState('');
const [pwd, setPwd] = useState('');
// const authCon = useContext(AuthContext);
return (
<div className="div-login">
<div className="div-login-logo">
{/* <img src={logo} alt="Logo"></img> */}
</div>
<div>
<form onSubmit={(e) => handleSubmit(e, email, pwd)}>
<input
className="credentials-input"
type="email"
value={email}
placeholder="Email Address"
required
onChange={(e) => setEmail(e.target.value)}
/>
<input
className="credentials-input"
type="password"
value={pwd}
placeholder="Password"
required
onChange={(e) => setPwd(e.target.value)}
/>
<button className="login-button" type="submit">
Log In
</button>
</form>
</div>
</div>
);
};
export default Login;
And finally Login.test.tsx shown below
import { fireEvent, render, screen } from '#testing-library/react';
import Login from './Login';
import * as CommonModule from './common';
jest.mock('./common');
test('Submit shoud work successfully', () => {
const mockLogin = jest.spyOn(CommonModule,'handleSubmit').mockImplementation();
const { getByRole } = render(<Login />);
const login_button = getByRole('button');
fireEvent.submit(login_button);
expect(mockLogin).toHaveBeenCalledTimes(1);
});
Test Result :

Reactjs not calling Firebase function Nodemailer

I've created a contact form in ReactJS and am trying to send an email to myself using Nodemailer with firebase functions. The email will consist of whatever the person has filled out in the contact form.
I have tried the firebase function using postman and it works, I successfully receive an email when the endpoint is tried.
However when I try to call it in my React app, nothing is sent, and there are no errors reported. I have looked online to see what I am doing wrong but no luck.
Here is my code.
firebase functions index.js
// import needed modules
const functions = require("firebase-functions");
const nodemailer = require("nodemailer");
const office365Email = functions.config().outlook365.email;
const office365Password = functions.config().outlook365.password;
// create and config transporter
const transporter = nodemailer.createTransport({
host: "smtp.office365.com",
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: office365Email,
pass: office365Password,
},
});
// export the cloud function called `sendEmail`
exports.sendEmail = functions.https.onCall((data, context) => {
// for testing purposes
console.log(
"from sendEmail function. The request object is:",
JSON.stringify(data.body)
);
const email = data.email;
const name = data.name;
const message = data.message;
// config the email message
const mailOptions = {
from: email,
to: office365Email,
subject: "New message from the nodemailer-form app",
text: `${name} says: ${message}`,
};
return transporter.sendMail(mailOptions).then(() => {
return { success: true };
}).catch(error => {
console.log(error);
});
});
here is my reactjs code:
import React, {useRef, useState} from "react";
import {useAuth} from "../contexts/AuthContext";
import {useHistory} from "react-router-dom";
import firebase from 'firebase/app';
import classes from "./SyncManagerDemo.module.scss";
import {Button, Container, Form} from "react-bootstrap";
export default function ContactUs() {
const nameRef = useRef();
const emailRef = useRef();
const messageRef = useRef();
const firmRef = useRef();
const history = useHistory();
const [error, setError] = useState("")
const [loading, setLoading] = useState(false)
const sendEmail = firebase.functions().httpsCallable('sendEmail');
async function handleSubmit(e) {
e.preventDefault()
console.log("nameRef: " + nameRef.current.value);
console.log("emailRef: " + emailRef.current.value);
console.log("messageRef: " + messageRef.current.value);
return /*const test =*/ await sendEmail({
name: nameRef.current.value,
email: emailRef.current.value,
message: messageRef.current.value
}).then(result => {
return console.log("message sent");
}).catch(error => {
console.log("error occurred.");
return console.log(error);
});
}
return (
<React.Fragment>
<div className={classes.body}>
<Container>
<div className={classes.body}>
<h2>Contact Us</h2>
<Form onSubmit={handleSubmit}>
<Form.Group id="email">
<Form.Label>Email</Form.Label>
<Form.Control type="email" ref={emailRef} required/>
</Form.Group>
<Form.Group id="name">
<Form.Label>Name</Form.Label>
<Form.Control type="text" ref={nameRef} required/>
</Form.Group>
<Form.Group id="message">
<Form.Label>Message</Form.Label>
<Form.Control type="text" ref={messageRef} required/>
</Form.Group>
<Form.Group id="firm">
<Form.Label>Firm</Form.Label>
<Form.Control type="text" ref={firmRef} required/>
</Form.Group>
<Button disabled={loading} className="w-100" type="submit">
Send
</Button>
</Form>
</div>
</Container>
</div>
</React.Fragment>
)
not sure if this helps but my postman POST request body I send through looks like this which works:
{
"data": {
"email": "my email#email.com",
"name": "test name",
"message": "hello world"
}
}
Any and all help is appreciated.

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.
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));
}
...

Update state after axios POST request instead of page refresh

I have a form with input fields 'title' and 'body', they are being added to MongoDB after submitting the form, but the new post item shows up only after I refresh the page (that of course is not how it should work), but I want to know what I am doing wrong and how to fix the handleSumbit function?
Here is my code:
import { useState, useEffect } from "react";
import axios from "axios";
import "./App.css";
function App() {
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const [posts, setPosts] = useState([]);
const url = "http://localhost:8005/";
useEffect(() => {
const fetchPosts = async () => {
const response = await axios(`${url}posts`);
setPosts(response.data);
};
fetchPosts();
}, []);
const handleTitleChange = (event) => {
setTitle(event.target.value);
};
const handleBodyChange = (event) => {
setBody(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
axios.post(`${url}posts`, { title: title, body: body })
.then((res) => {
console.log(res.data);
});
alert("Post added!");
setTitle("");
setBody("");
};
console.log(posts);
return (
<div className="App">
{posts.map((post) => (
<div className="post" key={post.id}>
<h4>{post.title}</h4>
<p>{post.body}</p>
</div>
))}
<form onSubmit={handleSubmit}>
<label>
Mew post:
<input
type="text"
name="title"
placeholder="Add title"
onChange={handleTitleChange}
/>
<input
type="text"
name="body"
placeholder="Add body"
onChange={handleBodyChange}
/>
</label>
<button type="submit">Add</button>
</form>
</div>
);
}
export default App;
The problem is that you didn't update the posts state after you sent the axios post request. Edit the below code block:
const handleSubmit = (event) => {
event.preventDefault();
axios.post(`${url}posts`, { title: title, body: body })
.then((res) => {
console.log(res.data);
// save the new post to posts
setPosts([...posts, res.data])
});
alert("Post added!");
setTitle("");
setBody("");
};

Resources