I have a project that make profile cards for users in react. When user create his card I'm tiring to show him how the card looks before he submit and create it.
At this moment the create card work good but I don't know how to show him the card at the same time.
My state update only when he is submit the form.
create component:
function CreatCard() {
const navigate = useNavigate();
const getUserData = JSON.parse(localStorage.getItem("data")).data;
console.log(getUserData.id);
const [bisCard, setBisCard] = useState({
businessName: "",
businessDescription: "",
businessAddress: "",
businessPhone: "",
businessImage: "",
userId: getUserData.id,
});
const handleCreateCard = async (e) => {
e.preventDefault();
const card = { bisCard };
console.log(card.bisCard);
const requestMethods = {
method: "POST",
headers: {
"Content-Type": "application/json",
token: getUserData.token,
},
body: JSON.stringify(card.bisCard),
};
console.log(getUserData.token);
try {
const response = await fetch(
"http://localhost:8000/cards/create",
requestMethods
);
if (response.ok) navigate("/cusomerPage");
else {
console.log(response.json());
}
} catch (err) {
console.log("!!!!", err);
}
};
const handleChangeName = (e) =>
setBisCard({ ...bisCard, businessName: e.target.value });
const handleChangeDescription = (e) =>
setBisCard({ ...bisCard, businessDescription: e.target.value });
const handleChangeAdress = (e) =>
setBisCard({
...bisCard,
businessAddress: e.target.value,
});
const handleChangephone = (e) =>
setBisCard({ ...bisCard, businessPhone: e.target.value });
const handleChangeImg = (e) =>
setBisCard({ ...bisCard, businessImage: e.target.value });
return (
<div>
<div className="creat-form-container">
<CardForm
handleCreateCard={handleCreateCard}
handleChangeName={handleChangeName}
handleChangeDescription={handleChangeDescription}
handleChangeAdress={handleChangeAdress}
handleChangephone={handleChangephone}
handleChangeImg={handleChangeImg}
/>
<div card-container>
<Card card={bisCard}></Card>
</div>
</div>
</div>
);
}
card component:
import DeleteCard from "../deleteCard/DeleteCard";
import "./Card.scss";
const Card = ({ card }) => {
// console.log(card);
return (
<div className="card col my-2 mx-2 ">
<DeleteCard card={card} />
<img
src={card.businessImage}
className="img-size rounded card-img-top "
alt="BusinessImage"
/>
<div className="card-body">
<h5 className="card-title">{card.businessName}</h5>
<p className="card-text">
<b> {card.businessPhone}</b>
</p>
<p className="card-text">{card.businessDescription}</p>
<p className="card-text">
<small className="text-muted">{card.businessAddress}</small>
</p>
</div>
</div>
);
};
export default Card;
thanks for help
Related
I am running into an issue where regardless of what component is clicked in a list of Job items, it returns the id of the last element only.
I have a key passed to the mapped list:
let activeListings = jobs.filter((job) => !job.isArchived);
activeListings?.map((job) => {
return (
<div key={job._id} className="bg-white w-8/12 py-4 my-4">
<Job
job={job}
setJob={setJobs}
handleShowDetailsToggle={handleShowDetailsToggle}
archiveToggler={archiveToggler}
setShowingResumeModal={setShowingResumeModal}
setShowingCoverLetterModal={setShowingCoverLetterModal}
showingResumeModal={showingResumeModal}
showingCoverLetterModal={showingCoverLetterModal}
getJobs={getJobs}
key={job._id}
/>
</div>
);
})
In the Job component, there is a button that when clicked opens a modal to select a file to upload and a preview.
Regardless of which Job component the Upload component is called from, it always gets passed the job._id from the final Job component listed.
Here is the resume modal component that opens on the button click:
import React, { useState } from "react";
import Upload from "../../Upload";
const AddNewResumeModal = (props) => {
const { setShowingResumeModal, job, getJobs, id } = props;
const [previewSource, setPreviewSource] = useState("");
return (
<div className="resume-modal-background">
<div className="resume-modal-container">
<button
className="close-modal-btn"
onClick={() => setShowingResumeModal(false)}
>
×
</button>
<h1 className="resume-modal-title">Upload Resume</h1>
<button onClick={() => console.log(job._id)}>Test2</button>
<Upload
resume={true}
setShowingResumeModal={setShowingResumeModal}
job={job}
getJobs={getJobs}
previewSource={previewSource}
setPreviewSource={setPreviewSource}
/>
<div></div>
</div>
</div>
);
};
export default AddNewResumeModal;
and the Upload component it renders:
import React, { useState } from "react";
import { Viewer } from "#react-pdf-viewer/core";
import "#react-pdf-viewer/core/lib/styles/index.css";
const URL = "http://localhost:8000";
const Upload = (props) => {
const {
setShowingResumeModal,
job,
getJobs,
previewSource,
setPreviewSource,
} = props;
const [fileInputState, setFileInputState] = useState("");
// const [previewSource, setPreviewSource] = useState("");
const handleFileInputChange = (e) => {
const file = e.target.files[0];
console.log(file);
previewFile(file);
};
const previewFile = (file) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
setPreviewSource(reader.result);
};
};
const handleSubmitFile = (e) => {
e.preventDefault();
if (!previewSource) return;
uploadFile(previewSource, job._id);
getJobs();
setShowingResumeModal(false);
};
const uploadFile = async (base64encodedFile, id) => {
console.log(base64encodedFile);
console.log(id);
try {
await fetch(`${URL}/upload/${id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ data: base64encodedFile }),
});
} catch (error) {
console.error(error);
}
};
return (
<div>
<form>
<input
type="file"
name="pdf"
id="pdf"
accept=".pdf"
onChange={handleFileInputChange}
value={fileInputState}
className="form-input"
onClick={() => console.log(job._id)}
/>
</form>
<div className="preview-container">
{previewSource ? (
<div className="viewer-container">
<Viewer fileUrl={previewSource} />
</div>
) : (
<div className="no-preview-source">Preview area</div>
)}
</div>
<button
onClick={handleSubmitFile}
type="submit"
className="upload-submit-btn"
>
Upload Resume
</button>
</div>
);
};
export default Upload;
Please help me understand how to correctly pair each job listing so that the correct id of the job is passed to the backend.
My projct is a note app where you can can add notes and delete notes. I want to get data from the database and show it but I have to delete note twice, add note or reload page to show the new data.
notesList.jsx
this is my main component
i send getNotes() to another component for i can get new datas
const NotesList = () => {
const [notes, setNotes] = useState([]);
const getNotes = async () => {
const getNoteInformation = {
email: localStorage.getItem("tokenEmail"),
};
const response = await axios.post(
"http://localhost:9000/api/note/get",
getNoteInformation
);
try {
setNotes(response.data.data);
} catch (error) {}
};
const handleAddNote = async (tasktext) => {
const addNoteInformation = {
email: localStorage.getItem("tokenEmail"),
taskText: tasktext,
date: moment(new Date()).locale("fa").format("YYYY/MM/DD").toString(),
};
if (addNoteInformation.email && addNoteInformation.taskText) {
try {
await axios.post(
"http://localhost:9000/api/note/add",
addNoteInformation
);
} catch (error) {}
}
};
const handleDeleteNote = async (id) => {
const deletedInformaion = {
email: localStorage.getItem("tokenEmail"),
noteId: id,
};
if (deletedInformaion.email && deletedInformaion.noteId) {
await axios.post(
"http://localhost:9000/api/note/deleted",
deletedInformaion
);
}
};
useEffect(() => {
getNotes();
}, []);
return (
<>
<Navbar />
<div className="container">
<div className="row">
{notes
.filter((notes) => notes != null)
.map((notes, index) => (
<Note
key={index}
text={notes.text}
date={notes.date}
id={notes._id}
deletenote={handleDeleteNote}
getnote={getNotes}
/>
))}
<AddNote getnote={getNotes} addnote={handleAddNote} />
</div>
</div>
</>
);
};
note.jsx
const Note = (props) => {
const handleDeleteNote = () => {
props.deletenote(props.id);
props.getnote();
};
return (
<>
<div className="col-lg-4 col-md-6 col-sm-12 p-4">
<div className="note d-flex flex-column">
<span className="note-top overflow-auto m-2 ps-2">{props.text}</span>
<div className="note-bottom d-flex justify-content-between flex-row-reverse mt-auto">
<small>{props.date}</small>
<MdDelete
onClick={handleDeleteNote}
className="delete-icon"
size="1.3rem"
color="#bb86fc"
/>
</div>
</div>
</div>
</>
);
};
addNote.jsx
const AddNote = (props) => {
let addNoteText = useRef();
const handleAddNote = async () => {
props.addnote(addNoteText.current.value);
props.getnote();
addNoteText.current.value = "";
};
return (
<div className="col-lg-4 col-md-6 col-sm-12 p-4">
<div className="add-note-box d-flex flex-column justify-content-between">
<div className="top-box">
<textarea
placeholder="یادداشت خود را وارد کنید ......"
class="form-control"
rows={7}
ref={addNoteText}
></textarea>
</div>
<BsFillPlusCircleFill
onClick={handleAddNote}
className="plus-icon"
size="1.3rem"
color="#bb86fc"
/>
</div>
</div>
);
};
You didn't update state after sending the respective add and delete request, that's why you need to refresh to get the updated data. This is the fix:
const handleAddNote = async (tasktext) => {
const addNoteInformation = {
email: localStorage.getItem("tokenEmail"),
taskText: tasktext,
date: moment(new Date()).locale("fa").format("YYYY/MM/DD").toString(),
};
if (addNoteInformation.email && addNoteInformation.taskText) {
try {
await axios.post(
"http://localhost:9000/api/note/add",
addNoteInformation
);
setNotes([...notes, addNoteInformation]); // update state using spread operator and put the new one to the end
} catch (error) {}
}
};
const handleDeleteNote = async (id) => {
const deletedInformaion = {
email: localStorage.getItem("tokenEmail"),
noteId: id,
};
if (deletedInformaion.email && deletedInformaion.noteId) {
await axios.post(
"http://localhost:9000/api/note/deleted",
deletedInformaion
);
setNotes(notes.filter(note => note.id !== id)) // update state using filter function
}
};
Alternativelly, when adding notes, you can update state using the response object from your request, since the id of newly created note maybe generated by your database. It dependes on the actual response object from the axios request:
const response = await axios.post();
setNotes([...notes, response.data]);
I'm trying to make an app where an 'Owner' can have multiple 'cars', I have my App.js file where the Owner enters there name and can enter there car details ('Car name' and 'Car Type'), a Owner can have multiple Cars, and when they click 'Add car entry' a Component where they enter there car details called 'OwnersCars' is repeated. Like so
to
If an owner fills out the input boxes in this component (For X amount of cars) then clicks 'Save Owner' i want the owner aswell as a list of all there cars to be saved into one State.
Currently i have my app.js file like this (count is used to know the number of OwnersCars divs)
import './App.css';
import React, {useState, useRef} from 'react';
import OwnersCars from './ownersCars';
function App() {
const [count, setCount] = useState(1)
const [OwnerInput, SetOwnerInput] = useState({
id: "",
Name: "",
cars: []
});
const [newCarInput, SetnewCarInput] = useState({
id: "",
Type: "",
CarName: ""
});
const removeDiv = () => {
//console.log('sw\nag')
setCount(count - 1)
}
const repeatDiv = () => {
//console.log('sw\nag')
setCount(count + 1)
}
const displayCarInput = (e) => {
//console.log(count, "<--key")
return ( ([...Array(count)].map((e, i) => <OwnersCars onAddNameCar={addNewCarNameHandler} onAddTypeCar={addNewCarTypeHandler}></OwnersCars> )))
}
const displayRemove = (e) =>{
if (count > 1) {
return (<button className='removeAnimalButton' onClick={removeDiv}> <dt> Remove Last Animal Entry</dt></button>)
}
}
const NameHandler = (e) => {
//console.log(e.target.value)
SetOwnerInput((prevState) => {
return { ...prevState, Name: e.target.value };
});
}
const submitHandler = (event) => {
event.preventDefault();
const value = Math.random().toString()
const OwnerData = {
id: value,
Name: OwnerInput.Name,
cars: [newCarInput]
};
console.log(OwnerData, "<--- ownerdata with cars data");
}
const addNewCarNameHandler = (values) => {
//console.log(values, "<---5")
SetnewCarInput((prevState) => {
return { ...prevState, CarName: values };
});
};
const addNewCarTypeHandler = (values) => {
//console.log(values, "<---5")
SetnewCarInput((prevState) => {
return { ...prevState, Type: values };
});
};
return (
<div>
<div>
<div>
<label for="exampleInputPassword1"></label>
<button onClick={submitHandler} ><dt>Save Owner</dt></button>
</div>
</div>
<hr/>
<div className="wrapper">
<div class="new-owner-div">
<h5>Owner</h5>
<hr/>
<form>
<div>
<input type="name" id="exampleInputClinic" placeholder="Owner Name" onChange={NameHandler}/>
</div>
</form>
</div>
<div class="new-owner-div-2">
<h5>Owners Cars</h5>
<hr/>
{displayCarInput()}
<div>
<button onClick={repeatDiv}> <dt> Add Car Entry</dt></button>
{displayRemove()}
</div>
</div>
</div>
</div>
);
}
export default App;
and i have my ownersCars.js file with the OwnersCars component like this
import React, {useState, useRef} from 'react';
function OwnersCars(props) {
const CarNameHandler = (e) => {
console.log(e.target.value)
props.onAddNameCar(e.target.value)
}
const CarTypeHandler = (e) => {
console.log(e.target.value)
props.onAddTypeCar(e.target.value)
}
return(
<div>
<div>
<div>
<h3>Car name</h3>
<span></span>
<h3>Type</h3>
</div>
<div>
<div>
<input placeholder="Car Name" onChange={CarNameHandler}/>
</div>
<span class="span1-box"></span>
<div class="height">
<input class="input-box-OA-2" placeholder="Car Type" onChange={CarTypeHandler}/>
</div>
<span class="span1-box"></span>
</div>
</div>
</div>
)
}
export default OwnersCars
but when i click save user it only saves the latest car entry!
Would anyone be able to help?
Sorry for the mess and lack of css i removed a bunch of things from the original code so it was easier to follow on StackOverflow. Also im fairly new to react so im sure theres alot of things that need to be changed for this to work.
You need to push to owner cars, every time you add a new car. Please find the code below for App.js changes. check repeatDiv. Similarly, you need to pop from cars the particular car with remove div which I leave it to you
import React, { useState, useRef } from "react";
import OwnersCars from "./Owner";
function App() {
const [count, setCount] = useState(1);
const [OwnerInput, SetOwnerInput] = useState({
id: "",
Name: "",
cars: []
});
const [newCarInput, SetnewCarInput] = useState({
id: "",
Type: "",
CarName: ""
});
const removeDiv = () => {
//console.log('sw\nag')
setCount(count - 1);
};
const repeatDiv = () => {
//console.log('sw\nag')
OwnerInput.cars.push(newCarInput);
setCount(count + 1);
};
const displayCarInput = (e) => {
//console.log(count, "<--key")
return [...Array(count)].map((e, i) => (
<OwnersCars
onAddNameCar={addNewCarNameHandler}
onAddTypeCar={addNewCarTypeHandler}
></OwnersCars>
));
};
const displayRemove = (e) => {
if (count > 1) {
return (
<button className="removeAnimalButton" onClick={removeDiv}>
{" "}
<dt> Remove Last Animal Entry</dt>
</button>
);
}
};
const NameHandler = (e) => {
//console.log(e.target.value)
SetOwnerInput((prevState) => {
return { ...prevState, Name: e.target.value };
});
};
const submitHandler = (event) => {
event.preventDefault();
const value = Math.random().toString();
const OwnerData = {
id: value,
Name: OwnerInput.Name,
cars: OwnerInput.cars
};
console.log(OwnerData, "<--- ownerdata with cars data");
};
const addNewCarNameHandler = (values) => {
//console.log(values, "<---5")
SetnewCarInput((prevState) => {
return { ...prevState, CarName: values };
});
};
const addNewCarTypeHandler = (values) => {
//console.log(values, "<---5")
SetnewCarInput((prevState) => {
return { ...prevState, Type: values };
});
};
return (
<div>
<div>
<div>
<label for="exampleInputPassword1"></label>
<button onClick={submitHandler}>
<dt>Save Owner</dt>
</button>
</div>
</div>
<hr />
<div className="wrapper">
<div class="new-owner-div">
<h5>Owner</h5>
<hr />
<form>
<div>
<input
type="name"
id="exampleInputClinic"
placeholder="Owner Name"
onChange={NameHandler}
/>
</div>
</form>
</div>
<div class="new-owner-div-2">
<h5>Owners Cars</h5>
<hr />
{displayCarInput()}
<div>
<button onClick={repeatDiv}>
{" "}
<dt> Add Car Entry</dt>
</button>
{displayRemove()}
</div>
</div>
</div>
</div>
);
}
export default App;
And the output with cars saved
This is for api re-rendering issue, I want to know that how to call one api after selecting a dropdown option.
Here it re-render infinite time after selecting an-option in drop-down. I call an client Api from client collection and show in client drop down after I select drop down and going to the infinite loop.
import Select from "react-select";
import Axios from "axios";
import React, { useState, useEffect } from "react";
export default function Form() {
const [hday, setHday] = useState(null);
const [date, setDate] = useState(null);
const [hdata, setHdata] = useState([]);
const [hid, setHid] = useState(""); //changed use state value null to []
const [client, setClient] = useState([]);
const [clientvalue, setClientValue] = useState(null);
const [clientId, setClientId] = useState(""); //changed use state value null to []
const [cemail, setCemail] = useState([]);
const [clientname, setClientname] = useState(null);
const [clientEmail, setClientEmail] = useState([]);
const [message, setMessage] = useState("");
const [fromField, setFromField] = useState("");
const [loading, setLoading] = useState(false);
const handleRequest = async (e) => {
if (clientvalue && hday && fromField && cemail && clientEmail && message !== "") {
if (message !== "") {
e.preventDefault();
setLoading(true);
console.log({
clientvalue,
hday,
fromField,
cemail,
clientEmail,
message,
});
const body = {
clientvalue,
hday,
fromField,
cemail,
clientEmail,
message,
};
await Axios.post("http://localhost:3002/mail", body, {
headers: {
"Content-type": "application/json",
},
})
.then((res) => {
alert("Email Sent Successfully");
setLoading(false);
console.log(res);
window.location.reload();
})
.catch((err) => {
console.log(err);
setLoading(false);
});
} else {
alert("Compose Email");
}
} else {
alert("Please fill all required filled");
}
};
const fromFieldChange = (obj) => {
setFromField(obj.target.value);
};
const handleQuillChange = (e) => {
setMessage(e.target.value);
};
function handleHolidayChange(obj) {
console.log("This is object country", obj);
setHday(obj);
setHid(obj._id);
setDate(null);
}
//client call (repetadely call)
const onChangeClient = (obj) => {
console.log("client object", obj);
console.log("client object id", obj._id);
setClientValue(obj);
setClientId(obj._id);
setClientname(obj.client_name);
};
// console.log("This is client id and name", clientId + " " + clientname);
//(issues repetadely execute)
async function emailClick() {
const url = `http://localhost:3002/api/getClientEmail/${clientId}/${clientname}`;
Axios.get(url)
.then((response) => {
const temp = response.data.map((e) => e.email);
setCemail(temp);
console.log("Client Email", cemail);
})
.catch((error) => {
console.log(error);
});
}
emailClick();
const changeDate = async function dateClick() {
const url = `http://localhost:3002/api/holiday_date/${hid}`;
await Axios.get(url)
.then((response) => {
// console.log("This is holiday date",response.data[0]['date_of_holiday']);
setDate(response.data.date_of_holiday);
// console.log("holiday year",date);
})
.catch((error) => {
console.log(error);
});
};
changeDate();
useEffect(
() => {
async function getHoliday() {
const url = `http://localhost:3002/api/holidays`;
await Axios.get(url)
.then((response) => {
setHdata(response.data);
console.log("this is holiday", response.data);
})
.catch((err) => {
console.log(err);
});
}
getHoliday();
async function getClient() {
const url = `http://localhost:3002/api/client`;
await Axios.get(url)
.then((response) => {
setClient(response.data);
console.log("this is client", response.data);
})
.catch((err) => {
console.log(err);
});
}
getClient();
///api/emailtemplates
async function getClientEmail() {
const url = `http://localhost:3002/api/emailtemplates`;
await Axios.get(url)
.then((response) => {
setClientEmail(response.data.map((e) => e.subject));
})
.catch((err) => {
console.log(err);
});
}
getClientEmail();
},
[date],
[cemail],
);
return (
<form onSubmit={handleRequest} method="post">
<div className="form">
<div className="form__wrapper">
<div className="form__title">
{/* title */}
<h4>Holiday</h4>
</div>
<div className="form__container">
<div className="form__containerItems">
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Client</label>
</div>
<div className="form__containerItemField">
<Select
onChange={onChangeClient}
placeholder="Select Client"
value={clientvalue}
options={client}
getOptionLabel={(x) => x.client_name}
getOptionValue={(x) => x._id}
/>
</div>
</div>
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Holiday</label>
</div>
<div className="form__containerItemField">
<Select
onChange={handleHolidayChange}
placeholder="Select Holiday"
value={hday}
options={hdata}
getOptionLabel={(x) => x.holiday_name}
getOptionValue={(x) => x._id}
/>
</div>
</div>
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Date</label>
</div>
<div className="form__containerItemField">
<input type="text" placeholder="date..." defaultValue={date} />
</div>
</div>
</div>
</div>
<div className="form__container">
<div className="form__containerItems">
{/* from */}
<div className="form__containerItem">
<div className="form__containerItemName">
<label>From</label>
</div>
<div className="form__containerItemField">
<input
type="email"
placeholder="Sender Email.."
// autoFocus="autoFocus"
value={fromField}
onChange={fromFieldChange}
/>
</div>
</div>
{/* to */}
<div className="form__containerItem">
<div className="form__containerItemName">
<label>To</label>
</div>
<div className="form__containerItemField">
<input type="text" placeholder="Client Emial.." defaultValue={cemail} />
</div>
</div>
{/* Subject */}
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Subject</label>
</div>
<div className="form__containerItemField">
<input type="text" placeholder="Write your Sub..." defaultValue={clientEmail} />
</div>
</div>
<div className="form__containerItem">
<div className="form__containerItemName">
<label>Compose Mail</label>
<button
disabled={loading}
onClick={handleRequest}
type="submit"
className="btn btn-info"
>
Send
</button>
</div>
</div>
<div className="form__containerItem">
<div className="container__composeMail">
<textarea
value={message}
onChange={handleQuillChange}
className="quill"
placeholder="Enter Content from here..."
/>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
);
}
I was coding along with Zero To Mastery web dev course. The app is called smartbrain. There is a signin method which doesn't run when I'm adding if statement, it should go to homepage, but its bouncing back to signin page. It only goes to homepage if put the routing function outside the if loop.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const database = {
users: [
{
id: '123',
name: 'john',
email: 'john#gmail.com',
password: 'cookies',
entries: 0,
joined: new Date(),
},
{
id: '124',
name: 'sally',
email: 'sally#gmail.com',
password: 'bananas',
entries: 0,
joined: new Date(),
},
],
};
app.get('/', (req, res) => {
res.json(database.users);
});
app.post('/signin', (req, res) => {
if (
req.body.email === database.users[0].email &&
req.body.password ===
database.users[0].password
) {
res.json('success');
} else {
res.status(400).json('error logging in');
}
});
app.post('/register', (req, res) => {
const { name, email, password } = req.body;
database.users.push({
id: '125',
name: name,
email: email,
password: password,
entries: 0,
joined: new Date(),
});
res.json(
database.users[database.users.length - 1]
);
});
app.get('/profile/:id', (req, res) => {
let found = false;
const { id } = req.params;
database.users.forEach((user) => {
if (user.id === id) {
found = true;
return res.json(user);
}
});
if (!found) {
res.status(400).json('user not found');
}
});
app.post('/image', (req, res) => {
let found = false;
const { id } = req.body;
database.users.forEach((user) => {
if (user.id === id) {
found = true;
user.entries++;
return res.json(user.entries);
}
});
if (!found) {
res.status(400).json('user not found');
}
});
app.listen(3001, () => {
console.log('App is running');
});
signin.js
import { React, Component } from 'react';
class Signin extends Component {
constructor(props) {
super(props);
this.state = {
signInEmail: '',
signInPassword: '',
// validUser: false,
};
}
onEmailChange = (event) => {
this.setState({
signInEmail: event.target.value,
});
};
onPasswordChange = (event) => {
this.setState({
signInPassword: event.target.value,
});
};
onSubmitSignIn = () => {
// console.log(this.state);
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword,
}),
})
.then((response) => response.json())
.then(data => {
if (data==='success'){
this.props.onRouteChange('home');
}
})
// this.props.onRouteChange('home');
};
render() {
const { onRouteChange } = this.props;
// console.log(this.state);
return (
<article className='br3 ba b--black-10 mv4 w-80 w-50-m w-25-l mw6 shadow-5 center'>
<main className='pa4 black-80'>
<form className='measure center'>
<fieldset
id='sign_up'
className='ba b--transparent ph0 mh0'>
<legend className='f2 fw6 ph0 mh0 center'>
Sign In
</legend>
<div className='mt3'>
<label
className='db fw6 lh-copy f6'
htmlFor='email-address'>
Email
</label>
<input
className='pa2 input-reset ba bg-transparent hover-bg-black hover-white w-80'
type='email'
name='email-address'
id='email-address'
onChange={this.onEmailChange}
/>
</div>
<div className='mv3'>
<label
className='db fw6 lh-copy f6'
htmlFor='password'>
Password
</label>
<input
className='b pa2 input-reset ba bg-transparent hover-bg-black hover-white w-80'
type='password'
name='password'
id='password'
onChange={this.onPasswordChange}
/>
</div>
{/* <label className='pa0 ma0 lh-copy f6 pointer'>
<input type='checkbox' /> Remember
me
</label> */}
</fieldset>
<div className=''>
<input
className='b ph3 pv2 input-reset ba b--black bg-transparent grow pointer f6 dib'
type='submit'
value='Sign in'
onClick={this.onSubmitSignIn}
/>
</div>
<div className='lh-copy mt3'>
<p
onClick={() =>
onRouteChange('register')
}
className='f6 link dim black db pointer'>
Register
</p>
{/* <a
href='#0'
className='f6 link dim black db'>
Forgot your password?
</a> */}
</div>
</form>
</main>
</article>
);
}
}
export default Signin;
See the commented code
this.props.onRouteChange('home');
If I uncomment this and comment the one in if loop, I get a success response from my server and it goes to home page. Another thing is that if the this.props.onRouteChange('home'); is inside the if loop I can see my username password on url bar as a query string. Any solution???
app.js
import React, { Component } from 'react';
import Navigation from './Components/Navigation';
import Logo from './Components/Logo';
import ImageLinkForm from './Components/ImageLinkForm';
import Rank from './Components/Rank';
import FaceRecognition from './Components/FaceRecognition';
import Signin from './Components/Signin';
import Register from './Components/Register';
import Particles from 'react-particles-js';
import Clarifai from 'clarifai';
import './App.css';
const particlesConfig = {
particles: {
number: {
value: 40,
density: {
enable: true,
value_area: 500,
},
},
},
};
const app = new Clarifai.App({
apiKey: 'c14191b446b14919afd059c9a0666edf',
});
class App extends Component {
constructor() {
super();
this.state = {
input: '',
imageURL: '',
box: {},
route: 'signin',
isSignedIn: false,
};
}
// componentDidMount() {
// fetch('http://localhost:3001/')
// .then((response) => response.json())
// .then((data) => console.log(data));
// }
calculateFaceLocation = (data) => {
const clarifaiFace =
data.outputs[0].data.regions[0].region_info
.bounding_box;
const image =
document.getElementById('inputimage');
const width = Number(image.width);
const height = Number(image.height);
// console.log(width, height);
return {
leftCol: clarifaiFace.left_col * width,
topRow: clarifaiFace.top_row * height,
rightCol:
width - clarifaiFace.right_col * width,
bottomRow:
height - clarifaiFace.bottom_row * height,
};
};
displayFaceBox = (box) => {
console.log(box);
this.setState({
box: box,
});
};
handleInput = (event) => {
this.setState({
input: event.target.value,
});
};
handleDetect = () => {
this.setState({
imageURL: this.state.input,
});
app.models
.predict(
Clarifai.FACE_DETECT_MODEL,
this.state.input
)
.then((response) =>
this.displayFaceBox(
this.calculateFaceLocation(response)
)
)
.catch((err) => console.log(err));
};
onRouteChange = (route) => {
if (route === 'signout') {
this.setState({ isSignedIn: false });
} else if (route === 'home') {
this.setState({ isSignedIn: true });
}
this.setState({ route: route });
};
render() {
return (
<div className='App'>
<Particles
params={particlesConfig}
className='particles'
/>
<Navigation
onRouteChange={this.onRouteChange}
isSignedIn={this.state.isSignedIn}
/>
{this.state.route === 'home' ? (
<div>
<Logo />
<div style={{ marginTop: '-90px' }}>
<Rank />
<ImageLinkForm
handleInput={this.handleInput}
handleDetect={this.handleDetect}
/>
<FaceRecognition
imageURL={this.state.imageURL}
box={this.state.box}
/>
</div>
</div>
) : this.state.route === 'signin' ? (
<Signin
onRouteChange={this.onRouteChange}
/>
) : (
<Register
onRouteChange={this.onRouteChange}
/>
)}
</div>
);
}
}
export default App;
The only reason it would be failing is because the data response you're getting through fetch inside the if block (not loop) is certainly not equal to 'success'.
Try console logging the response.
Also, in your signin route, you're only checking the email and password are equal to the first user's in database array, so maybe you are only checking with the second user.
It actually the tag that was causing the problem. Removed it and now everything is fine. Its still in testing phase so i was only checking for the first user. Thanx a lot though for replying