data undefined in React Hook Form inside a NPM input fields - javascript

I´m using a npm of inputs plus react hooks but when i submit the data i get undefined values in my console. I tried using the default input tags and works fine, the data i send shows perfectly. Any suggestions? is it possible to work with this NPM and react hook form or should i use the default data (Something that i don´t really like to do)
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import Nav from "./Navbar";
import Footer from "./Footer";
import { FormField } from 'react-form-input-fields';
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { useForm } from "react-hook-form";
import { faEye,faEyeSlash } from '#fortawesome/free-solid-svg-icons';
import 'react-form-input-fields/dist/index.css';
function Login() {
const {register, handleSubmit } = useForm();
const eye = <FontAwesomeIcon icon={faEye} />
const closeEye = <FontAwesomeIcon icon={faEyeSlash} />
const [passwordShown, setPasswordShown] = useState(false);
let [email, setEmail] = useState("");
let [password, setPassword] = useState("");
const togglePasswordVisiblity = () => {
setPasswordShown(passwordShown ? false : true);
};
const onSubmit = (data) => {
console.log(data)
}
return (
<div className="page-container">
<div className="content-wrap">
<Nav />
<div className="div-login-form">
<h1 className="title">Login</h1>
<form className="login-form" onSubmit={handleSubmit(onSubmit)}>
<FormField
type="email"
standard="labeleffect"
value={email}
keys={'email'}
name="email"
effect={'effect_1'}
handleOnChange={(value) => setEmail(value)}
{...register("email")}
placeholder={'Enter Email'} />
<div className="input-password">
<div className="icon-eye">
<i onClick={togglePasswordVisiblity} className="icon"> {passwordShown ? eye : closeEye} </i>
</div>
<FormField
type={passwordShown ? "text" : "password"}
standard="labeleffect"
value={password}
keys={'password'}
name="password"
effect={'effect_1'}
handleOnChange={(value) => setPassword(value)}
{...register("password")}
placeholder={'Enter Password'} />
</div>
<button className="button-shop" type="submit">
Log in
</button>
</form>
</div>
</div>
<Footer />
</div>
);
}
export default Login;

You're not passing anything into your onSubmit function.
Rewrite it to something like this with your current setup:
onSubmit={() =>
handleSubmit(onSubmit({ email: email, password: password }))
}
Here's a minimal sandbox example
Aside
By the way, NPM is a package manager, not a component or element provider like you're referring to it by. Check out the useState docs for a good intro to states and React development.

Related

Problem while passing useState variable from one JSX file to another

(CreateColumn.jsx)
import React, { useState, useEffect } from "react";
import Axios from "axios";
import "./styles.css";
function CreateColumn() {
let [val1, setVal1] = useState("0");
let [val2, setVal2] = useState("0");
let [secName, setSecName] = useState("");
let [goAttendance, setGoAttendance] = useState(0);
function valueChanged(event) {
const checkChecked = event.target.id;
// console.log(checkChecked);
if (checkChecked === "section1") {
setVal1("1");
setVal2("0");
setSecName("Section 1");
} else if (checkChecked === "section2") {
setVal2("1");
setVal1("0");
setSecName("Section 2");
} else {
setVal1("0");
setVal2("0");
setSecName("");
}
}
useEffect(() => {
Axios.get("http://localhost:9000/createColumn").then((response) => {
setSecName(response.data);
});
}, []);
function sendColumn(event) {
setGoAttendance(1);
Axios.post("http://localhost:9000/createColumn", { secName, goAttendance });
}
return (
<div>
<form className="form-body">
<div className="form-check check-line center-col">
<input
className="form-check-input"
type="checkbox"
id="section1"
name="section"
value={val1}
checked={val1 === "1"}
onChange={valueChanged}
/>
</div>
<div className="form-check check-line center-col">
<input
className="form-check-input"
type="checkbox"
id="section2"
name="section"
value={val2}
checked={val2 === "1"}
onChange={valueChanged}
/>
</div>
<div className="submit-btn d-grid gap-2 d-md-flex justify-content-md-center">
<button
type="submit"
className="btn btn-lg btn-primary"
onClick={sendColumn}
>
Create
</button>
</div>
</form>
</div>
);
}
export default CreateColumn;
(Attendance.jsx)
import React, { useState, useEffect } from "react";
import Axios from "axios";
import TableTitle from "./TableTitle";
import Pagination from "./Pagination";
import "./styles.css";
function Attendance() {
const [attedanceList, setAttedanceList] = useState([]);
useEffect(() => {
Axios.get("http://localhost:9000/attendance/" + ****WANT TO USE secName FROM CreateColumn.jsx HERE****).then(
(response) => {
setAttedanceList(response.data.data.values);
}
);
}, []);
function sendAllValues(event) {
Axios.post("http://localhost:9000/attendance", { attedanceList });
}
return (
<form className="form-body">
<TableTitle />
<Pagination data={attedanceList} />
<div className="submit-btn d-grid gap-2 d-md-flex justify-content-md-center">
<button
type="submit"
className="btn btn-lg btn-primary"
onClick={sendAllValues}
>
Submit
</button>
</div>
</form>
);
}
export default Attendance;
(App.jsx)
import React, { useState } from "react";
import Attendance from "./Attendance";
import CreateColumn from "./CreateColumn";
function App() {
return (
<div>
<CreateColumn />
**WANT TO USE goAttendance FROM CreateColumn.jsx HERE** && <Attendance />
</div>
);
}
export default App;
I wanna use useState variables (secName and goAttendance) from Column.jsx in Attendance.jsx and App.jsx (where I have marked as WANT TO USE...). How is it possible?
More precisely, I wanna use secName from Column.jsx into Attendance.jsx.
Also, I wanna use goAttendance from Column.jsx into App.jsx
I tried so many things for hours but sometimes it breaks my code or simply have to change a lot which makes the code more messy and buggy.
As I can see CreateColumn and Attendence are the child components of App. You want to create a state and use it in app where as you want to set it in its child component. What I will suggest is to create the state and setState function on app level and then pass the state and setState function as props in the child component. I will suggest you to see this to know more about props.
in app.jsx
let [val1, setVal1] = useState("0");
let [val2, setVal2] = useState("0");
let [secName, setSecName] = useState("");
let [goAttendance, setGoAttendance] = useState(0);
const [attedanceList, setAttedanceList] = useState([]);
// while calling the components
return(
<>
<CreateColumn val1={val1}, val2={val2}, secName={secName}, ....../>
<Attendance val1={val1}, val2={val2}, secName={secName}, ....../>
</>
)
in CreateColumn and Attendence while declaring the components write
function Attendance({val1, val2, secName, setVal1, ...})
and then use the states and setStates in app.jsx

My topbar duplicates since adding axios and importing the user image with axios and react

I would like to know why my "topbar" is duplicated when I only want one. And it's since I did my import of the user image via axios and added the .map in the return. I really don't understand why if someone could help me that would be nice. Thanks in advance
import "./topbar.css"
import { Search } from '#mui/icons-material'
import { useState, useEffect, Fragment } from 'react'
import axios from "axios"
function Home() {
const [user, setPosts] = useState([])
useEffect(() => {
console.log("chargement ok")
const fetchData = async () => {
const result = await axios.get(
'http://localhost:4200/api/user/')
setPosts(result.data)
}
fetchData();
}, [])
return (
<Fragment>
{ user
? user.map((users,topbar) => ( <div key={topbar} className="topBarContainer">
<div className="topBarLeft">
<span className="logo">Groupomania</span>
</div>
<div className="topBarCenter">
<div className="searchBar">
<Search className="searchIcon" />
<input placeholder="Vous cherchez quelque chose ?" className="searchInput" />
</div>
</div>
<div className="topBarRight">
<div className="topBarLinks">
<span className="topBarLink">Page d'acceuil</span>
<span className="topBarLink">Deconnexion</span>
</div>
<img src={users.picture} alt="Photo de profil de l'utilisateur" className="topBarImg" />
</div>
</div>))
: (<p></p>)
}
</Fragment>
)
}
export default Home
I'm not sure why, but it may be because of your key.
Some patterns to fix first:
const [user, setPosts] = useState([]) -> const [posts, setPosts] = useState([])
you don't have to use the word Fragment: -> <>
Normally in a .map params are used like this posts.map((post, index) => ...)
posts ? post.map(...) : null
Edit: of course you have to remove your topbar from your .map(...)
Now try with a better key than "topbard" that is the index in the array ... try post.id that should be uniq
Edit solution:
import "./topbar.css";
import { Search } from "#mui/icons-material";
import { useState, useEffect, Fragment } from "react";
import axios from "axios";
function Home() {
const [user, setUser] = useState();
useEffect(() => {
console.log("chargement ok");
const fetchData = async () => {
const result = await axios.get("http://localhost:4200/api/user/");
setUser(result.data);
};
fetchData();
}, []);
return (
<div className="topBarContainer">
<div className="topBarLeft">
<span className="logo">Groupomania</span>
</div>
<div className="topBarCenter">
<div className="searchBar">
<Search className="searchIcon" />
<input
placeholder="Vous cherchez quelque chose ?"
className="searchInput"
/>
</div>
</div>
<div className="topBarRight">
<div className="topBarLinks">
<span className="topBarLink">Page d'acceuil</span>
<span className="topBarLink">Deconnexion</span>
</div>
{user && <img
src={user.picture}
alt="Photo de profil de l'utilisateur"
className="topBarImg"
/>}
</div>
</div>
);
}
export default Home;
As the map is rendering the topbar for every user, you get as many topbars as there are users.
The map function should be inside the top bar container div.
<div key={key} className="topBarContainer">
{ user.map(...) }
</div>
This is because your are making the topbar inside the loop,So you are getting a topbar per user.

Cannot read properties of undefined (reading *)

Hey I am learning reactjs as much as i have learned I am trying to make note app
my code given below
my App.js file
import React , {useEffect, useState} from "react"
import { nanoid } from "nanoid"
import Editor from './Note/Editor'
import Sidebar from "./Note/Sidebar"
function App() {
const [notes , setNotes] = useState(JSON.parse(localStorage.getItem("notes"))||[])
const [currentNoteID , setCurrentNoteID] = useState(false)
useEffect(()=>{
localStorage.setItem("notes" , JSON.stringify(notes))
},[notes])
function createNewNotes(){
const newNotes = {
id: nanoid(),
title:"untitled",
body: "sdasda",
lastModified: Date.now()
}
setNotes(prevNote => [newNotes , ...prevNote])
setCurrentNoteID(newNotes.id)
}
function deleteNote(noteID){
setNotes(prevNote => prevNote.filter(note=> note.id !== noteID ))
}
function getNotes(){
return notes.find((note)=> note.id === currentNoteID)
}
return (
<div className="note">
<Sidebar
notes={notes}
createNewNotes={createNewNotes}
currentNoteID={currentNoteID}
setCurrentNoteID={setCurrentNoteID}
deleteNote={deleteNote}
/>
<Editor
notes={getNotes()}
currentNoteID={currentNoteID}/>
</div>
);
}
export default App;
my Sidebar.js file
import React from 'react'
import './style.css'
export default function Sidebar(props){
return(
<>
<div className='sidebar' >
<div className='sidebar-header'>
<h3>Notes</h3>
<button className='add' onClick={props.createNewNotes} >Add</button>
</div>
{ props.notes.map((note)=>{
return(
<div key={note.id}
className={`${note.id===props.currentNoteID ? "active" : ""}`}
onClick={()=>props.setCurrentNoteID(note.id)}
>
<div>
<div className="sidebar-tab">
<div className='sidebar-title'>
<p className='title'>Untitled</p>
<button className='delete' onClick={()=>props.deleteNote(note.id)}>Delete</button>
</div>
<p className='note-preview'>summary of text</p>
</div>
</div>
</div>
)
})}
</div>
</>
)
}
my Editor.js file
import React , {useState} from "react";
import './style.css'
export default function Editor(props){
const [edit , setEdit] = useState(props.notes)
function handleChange(event){
const {name , value} = event.target
setEdit(prevNote=> {
return {
...prevNote,
[name] : value
}
})
}
if(!props.currentNoteID)
return <div className="no-note">no note active</div>
return(
<>
<div className="main">
<input type="text" className="main-input" name="title" placeholder="Enter title here" value={edit.title} onChange={handleChange} autoFocus/>
<textarea className="main-textarea" name="body" placeholder="Type your notes" value={edit.body} onChange={handleChange} />
<div className="preview">
<h1 className="preview-title">{edit.title}</h1>
<div className="main-preview">{edit.body}</div>
</div>
</div>
</>
)
}
whenever i click add button or any sidebar button it shows me error
Uncaught TypeError: Cannot read properties of undefined (reading 'title')
please help me out how to fix this issue
You're expecting getNotes (which should probably be named getActiveNote, IMHO) to re-run every time notes or currentNoteID change.
To achieve this, you have to declare it as a callback (useCallback) and to declare its dependencies. Also you want to place the result in state (e.g: activeNote):
const getActiveNote = useCallback(
() => notes.find((note) => note.id === currentNoteID),
[notes, currentNoteID]
);
const [activeNote, setActiveNote] = useState(getActiveNote());
useEffect(() => {
setActiveNote(getActiveNote());
}, [getActiveNote]);
// ...
<Editor note={activeNote} />
... at which point, you no longer need the currentNoteID in the <Editor /> as you can get it from props.note.id.
See it working here: https://codesandbox.io/s/crazy-glade-qb94qe?file=/src/App.js:1389-1448
Note: the same thing needs to happen in <Editor>, when note changes:
useEffect(() => setEdit(note), [note]);

React-draft-wysiwyg editor contents not editable

I'm building a simple blog app, and have a working editor to publish posts. I am now trying to implement one for the user to update a previous post. The editor state gets updated to the correct content, but it is not editable. I have also tried using a different editor and had the same problem. Does anyone have an idea as to what can be causing this? My best guess is that it has to do with how the data is loaded into the editor.
This is the function to update editorstate passed into the component using useContext
const updateTextDescription = (state) => {
setEditorState(state);
};
This is the update page.
import React from "react";
import classes from "./UpdateModal.module.css";
import './UpdateModal.css';
import { useBlogCtx } from "../../context/BlogContext";
import { EditorState, ContentState, convertFromHTML } from "draft-js";
import "../../../node_modules/draft-js/dist/Draft.css";
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import './UpdateModal.css';
import 'draft-js/dist/Draft.css';
function UpdateModal(props) {
const {
updatePost,
updateModalHandler,
setTitle,
setImage,
setPost,
currentId,
title,
image,
post,
updateTextDescription,
} = useBlogCtx();
const blocksFromHTML = convertFromHTML(post);
const content = ContentState.createFromBlockArray(
blocksFromHTML.contentBlocks,
blocksFromHTML.entityMap
);
const editorDataState = EditorState.createWithContent(content);
return (
<div
onClick={() => {
updateModalHandler();
}}
className={classes.backdrop}
>
<form onClick={(e) => e.stopPropagation()} className={classes.form}>
<label htmlFor="title">Title</label>
<input
id="title"
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<label htmlFor="image">Image(URL)</label>
<input
id="image"
type="text"
value={image}
onChange={(e) => setImage(e.target.value)}
/>
<label htmlFor="post">Post</label>
<Editor
editorState={editorDataState}
onEditorStateChange={updateTextDescription}
wrapperClassName="rich-editor demo-wrapper"
editorClassName="demo-editor"
/>
<div className={classes.buttons}>
<button className={classes.cancel} onClick={updateModalHandler}>
Cancel
</button>
<button
className={classes.update}
onClick={() => {
updatePost(currentId);
}}
>
Update
</button>
</div>
</form>
</div>
);
}
export default UpdateModal;
This is what the editor looks like. editor
Content correctly gets set to editor state, just not editable.

I have already imported useState in my React webpage but it is still showing compilation error

I have already imported the useState but it is still showing compilation error.
The name of my web page is CreatePost.js
import React, { useState } from 'react';
const createPost = () => {
/* We will use the 'useState' hooks to get the value from the text fields. */
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const [image, setImage] = useState("");
const postDetails = () => {
const data = new FormData();
data.append("file", image);
data.append("upload_preset", "insta-clone");
data.append("cloud_name", "rishavsinghh-cloud");
fetch("https://api.cloudinary.com/v1_1/rishavsinghh-cloud/image/upload", {
method: "post",
body: data
}).then(res => res.json()).then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
}
return (
<div className="card auth-card input-field" style={{ maxWidth:"500px", padding: "20px" }}>
<h2 className="cardHeading">Create Post</h2>
<input type="text" placeholder="Title" value={title} onChange={(event) => setTitle(event.target.value)} />
<input type="text" placeholder="Body" value={body} onChange={(event) => setBody(event.target.value)} />
<div className="file-field input-field">
<div className="btn">
<span>Upload Image <i class="fa fa-upload"></i></span>
<input type="file" value={image} onChange={(event) => setImage(event.target.files[0])} />
</div>
<div className="file-path-wrapper">
<input className="file-path validate" type="text" placeholder="Upload image" />
</div>
</div>
<button class="btn waves-effect waves-light #64b5f6 blue darken-1" onClick={ () => postDetails() } >Create Post <i class="fa fa-pencil"></i></button>
</div>
);
}
export default createPost;
The error I am getting is this :-
Just Change your component name from createPost to CreatePost. Because in react component name should start with Upper case letter.
change component name capital, like this CreatePost
https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type
Capitalize the Component Name
const CreatePost = () => {
//everything else
}
export default CreatePost
Capitalization of component names is a requirement in React so you need to change createPost to CreatePost and the error should be fixed.
More info from the ReactJs Docs: (https://reactjs.org/docs/components-and-props.html)
React treats components starting with lowercase letters as DOM tags.
For example, represents an HTML div tag, but
represents a component and requires Welcome to be in scope.
This compilation error is due to the capitalization of the component name. Rename the component name from createPost to CreatePost. Also, make sure that your filename should have the same format as the component name.
For Example:
CreatePost.js

Categories