How to display array data in form field in Ionic ReactJS? - arrays

I have some data fetched from Laravel API and stored in an array. I would like to display the value of the data in the form field so that users can edit the value. The array is as follows:
Array Data
I can display the other field data e.g si_t_street1 that is not being stored in an array simply by using the variable name as the property value of 'name' of the field.
Data Not Stored In Array
Below is the snippet of my code:
import React, { useContext, useEffect, useState } from 'react';
import { useForm } from "react-hook-form";
import { yupResolver } from '#hookform/resolvers/yup';
import * as Yup from 'yup';
import * as api from '../../services/api';
import { IonHeader, IonToolbar, IonButtons, IonBackButton, IonTitle, IonContent, IonButton, IonAlert, IonLoading, IonModal } from '#ionic/react';
import { NavContext } from "#ionic/react";
const AbroadApp: React.FC = (props: any) => {
const { id } = props.match.params.id ?? ``;
const isAddMode = (props.match.params.id) ? false : true;
const { register, handleSubmit, reset, setValue, errors, formState } = useForm({
resolver: yupResolver(validationSchema)
});
function onSubmit(data: any) {
return isAddMode
? createRegAbroad(data)
: updateRegAbroad(id, data);
}
useEffect(() => {
if (!isAddMode) {
api.getRegAbroadById(props.match.params.id).then(regAbroad => {
let fields = [
'si_t_street1',
'si_t_street2',
'si_t_street3',
'street1'
];
let regAbroadArr: any = [];
regAbroadArr.push(regAbroad.data.data);
fields.map(field => {
setValue(field, regAbroadArr[0][field])
})
setLoading(false)
});
}
}, []);
return (
<>
<IonContent>
<form onSubmit={handleSubmit(onSubmit)} onReset={reset}>
<input name="id" ref={register} type="hidden" autoComplete="off" />
<div className="row">
<div className="col-12">
<label>
Street 1{" "}
<span className="text-danger">*</span>
</label>
<div className="form-group">
<input name="si_t_street1" ref={register} className={`form-control ${errors.si_t_street1 ? 'is-invalid' : ''}`} type="text" autoComplete="off" />
<div className="invalid-feedback">
{errors.si_t_street1?.message}
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-12">
<label>
Street 1{" "}
<span className="text-danger">*</span>
</label>
<div className="form-group">
<input name="street1" ref={register} className={`form-control ${errors.street1 ? 'is-invalid' : ''}`} type="text"
autoComplete="off" value={country[0].street1} />
<div className="invalid-feedback">
{errors.street1?.message}
</div>
</div>
</div>
</div>
</form>
</IonContent>
</>
);
}
export default AbroadApp;
I tried getting the value of street1 property of the country array but the above code throws an error: cannot find name 'Country'. What is the right way to get the value to display?

It's unclear where you've defined your "country" variable.

Related

Using useEffect in react js to sent google rechaptha token

Hi i want implementation google rechapta using react, this is my react code
import { useForm } from 'react-hook-form';
import { useHistory } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import swal from 'sweetalert';
import ReCAPTCHA from "react-google-recaptcha";
const ContactForm = (props) => {
const {submitBtnClass } = props;
const { register, handleSubmit } = useForm();
const [token, setToken] = useState();
const history=useHistory();
const recaptchaRef = React.useRef();
function onChange(value) {
console.log("Captcha value:", value);
setToken(value);
}
useEffect(()=>{
document.getElementById("contact_tokenVal").value = token;
//const value = props.value
//setToken(value)
},[token]);
const onSubmit = data_api => {
axios
.post('http://localhost/erlanggastudio-rest-api/contact.php',data_api)
.then(res=>{
console.log(data_api);
history.push('/onepage-3');
swal(res.data.title, res.data.text, res.data.icon);
})
.catch(err => {
console.log(err);
});
};
return (
<form id="contact-form" onSubmit={handleSubmit(onSubmit)}>
<div className="row">
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_name" name="contact_name" placeholder="Nama" {...register('contact_name')} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_email" name="contact_email" placeholder="E-Mail" {...register('contact_email')} required />
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_mobilephone" name="contact_mobilephone" placeholder="No Telepon" {...register('contact_mobilephone')} required/>
</div>
<div className="col-md-6 mb-30">
<input className="from-control" type="text" id="contact_website" name="contact_website" placeholder="Website Anda" {...register('contact_website')} />
</div>
<div className="col-12 mb-30">
<textarea className="from-control" id="contact_message" name="contact_message" placeholder="Isi Pesan" {...register('contact_message')} required ></textarea>
</div>
<div className="col-12 mb-30">
<input className="from-control" type="hidden" id="contact_serverKey" name="contact_serverKey" value="6Lea50IhAAAAAAtfj-sElz7biY8WlDgrNwy7M7Tx" {...register('contact_serverKey')} />
<input className="from-control" type="hidden" id="contact_siteKey" name="contact_siteKey" value="6Lea50IhAAAAAEgdIvB6xUJ8KJCUyO-xKpPnA0fO" {...register('contact_siteKey')} />
<textarea className="from-control" id="contact_tokenVal" name="contact_tokenVal" defaultValue={token} {...register('contact_tokenVal')} />
</div>
<div className="col-md-6 mb-30">
<ReCAPTCHA
ref={recaptchaRef}
sitekey="6Lea50IhAAAAAEgdIvB6xUJ8KJCUyO-xKpPnA0fO"
onChange={onChange}
/>
</div>
</div>
<div className="btn-part">
<button className={submitBtnClass ? submitBtnClass : 'readon learn-more submit'} type="submit">Kirim</button>
</div>
</form>
);
}
export default ContactForm;
when the code running the view is like this :
i want to sent rechapta token using
<textarea className="from-control" id="contact_tokenVal" name="contact_tokenVal" defaultValue={token} {...register('contact_tokenVal')} />
after user klik rechapta, end will sent to server using axios, but i have some problem when sent the data to API Server using axion the rechapta token is blank like this screenshot :
my question is how to sent the rechapta token?, i'm using document.getElementById in useEffect, but still the value after sent is blank

Download URL from storage not transferring to firestore - React [duplicate]

This question already has answers here:
The useState set method is not reflecting a change immediately
(15 answers)
Why does calling react setState method not mutate the state immediately?
(9 answers)
Closed 7 months ago.
I am trying to add the imgUrl uploaded to firestore but it's not working. The url is generated and the image is stored in firebase storage but I can't seem to pass that URL as a field into Firestore
This is my code
import React, {useEffect, useState} from "react";
import ReactTagInput from "#pathofdev/react-tag-input";
import "#pathofdev/react-tag-input/build/index.css";
import {db, storage} from "../firebase";
import { getDownloadURL, ref, uploadBytes, listAll} from "firebase/storage";
import {
addDoc,
collection,
getDoc,
serverTimestamp,
doc,
updateDoc,
} from "firebase/firestore";
import { toast } from "react-toastify";
import { v4 } from 'uuid';
import {useNavigate} from "react-router-dom";
const initialState = { // initial state for our form
title: "",
tags: [],
trending: "no",
category: "",
description: "",
imgUrl: ""
}
const categoryOption = [
"Fashion",
"Technology",
"Food",
"Politics",
"Sports",
"Business"
]
export default function AddEditBlog({ user }) {
let urlDownload
const [form, setForm] = useState(initialState)
const [imageUpload, setImageUpload] = useState()
const [imageList, setImageList] = useState([])
const navigate = useNavigate()
const imageListRef = ref(storage, "images/") // to use in useEffect (listAll), because we
// wanna access all the files inside the images folder
const { title, tags, category, trending, description, imgUrl} = form;
const uploadImage = () => {
if(imageUpload == null) return; // if there's no image, return and get out of this function
uploadBytes(imageRef, imageUpload).then((snapshot)=> {
getDownloadURL(snapshot.ref).then((url) => {
// setImageList((prev) => [...prev, url])
console.log("url", url)
toast.info("Image upload to firebase successfully");
setForm((prev) => ({ ...prev, imgUrl: url }))
console.log("form", form)
})
})
}
const handleChange = (event) => {
setForm({...form, [event.target.name]: event.target.value})
}
const handleTags = (tags) => {
setForm({ ...form, tags})
}
const handleTrending = (event) => {
setForm({ ...form, trending: event.target.value })
}
const onCategoryChange = (event) => {
setForm({ ...form, category: event.target.value })
}
const handleSubmit = async (event) => {
event.preventDefault()
if (category && tags && title && description && trending && imgUrl) {
try {
console.log("url", urlDownload)
await addDoc(collection(db, "blogs"), {
...form,
timestamp: serverTimestamp(),
author: user.displayName,
userId: user.uid
})
toast.success("Blog created successfully");
} catch(error) {
console.log(error)
}
} else {
console.log("complete form")
}
navigate("/")
}
return(
<div className="container-fluid mb-4">
<div className="container">
<div className="col-12">
<div className="text-center heading py-2">
Create Blog
</div>
</div>
<div className="row h-100 justify-content-center align-items-center">
<div className="col-10 col-md-8 col-lg-6">
<form className="row blog-form" onSubmit={handleSubmit}>
<div className="col-12 py-3">
<input
type="text"
className="form-control input-text-box"
placeholder="Title"
name="title"
value={title}
onChange={handleChange}
/>
</div>
<div className="col-12 py-3">
<ReactTagInput
tags={tags}
placeholder="Tags"
onChange={handleTags}
/>
</div>
<div className="col-12 py-3">
<p className="trending">Is it trending blog ?</p>
<div className="form-check-inline mx-2">
<input
type="radio"
className="form-check-input"
value="yes"
name="radioOption"
checked={trending === "yes"} //if trending is yes select checked button
onChange={handleTrending}
/>
<label htmlFor="radioOption" className="form-check-label">
Yes
</label>
<input
type="radio"
className="form-check-input"
value="no"
name="radioOption"
checked={trending === "no"} //if trending is not select checked button
onChange={handleTrending}
/>
<label htmlFor="radioOption" className="form-check-label">
No
</label>
</div>
</div>
<div className="col-12 py-3">
<select
value={category}
onChange={onCategoryChange}
className="catg-dropdown"
>
<option>Please select category</option>
{categoryOption.map((option, index) => (
<option value={option || ""} key={index}>
{option}
</option>
))}
</select>
</div>
<div className="col-12 py-3">
<textarea
className="form-control description-box"
placeholder="Description"
value={description}
name="description"
onChange={handleChange}
/>
</div>
<div className="mb-3">
<input
type="file"
className="form-control"
onChange={(event)=> {
setImageUpload(event.target.files[0])
}}
/>
</div>
<div className="col-12 py-3 text-center">
<button
className="btn btn-add"
type="submit"
onClick={uploadImage}
>
Submit
</button>
</div>
</form>
</div>
</div>
</div>
</div>
)
}
Everything else loads successfully. The console log I do of the url returns the correct URL so I don't know why I can't pass it into firestore

React Hook Form with file just submitting fakepath

I'm trying to add an <Input type="file" to my react-hook-form, but it submit a C:\fakepath when I submit the form.
import React from "react";
import { Controller, useForm } from "react-hook-form";
import { Button, Form, Label, Input } from "reactstrap";
const App = () => {
const {
handleSubmit,
control,
setValue,
formState: { errors }
} = useForm();
const submitData = (data) => {
console.log(data);
};
return (
<div className="row">
<div className="col-sm-12 col-md-12 col-xl-12">
<Form onSubmit={handleSubmit(submitData)}>
<div className="row">
<div className="col-sm-6">
<Label for="file">File</Label>
<Controller
name="file"
control={control}
render={({ field }) => (
<Input {...field} type="file" id="file" />
)}
/>
</div>
</div>
<Button type="submit" color="primary">
Submit
</Button>
</Form>
</div>
</div>
);
};
export default App;
Here is the sandbox: https://codesandbox.io/s/morning-water-hyi9o
How can I use files with react-hook-form?
Thanks
You can find a solution here: https://github.com/react-hook-form/react-hook-form/discussions/5394#discussioncomment-848215
Here is another way to achieve that with register:
import React from "react";
import { useForm } from "react-hook-form";
import { Button, Form, Label, Input } from "reactstrap";
const App = () => {
const { register, handleSubmit } = useForm();
const submitData = (data) => {
console.log(data);
};
const { ref, ...field } = register("file");
return (
<div className="row">
<div className="col-sm-12 col-md-12 col-xl-12">
<Form onSubmit={handleSubmit(submitData)}>
<div className="row">
<div className="col-sm-6">
<Label for="file">File</Label>
<Input {...field} innerRef={ref} type="file" id="file" />
</div>
</div>
<Button type="submit" color="primary">
Submit
</Button>
</Form>
</div>
</div>
);
};
export default App;
I had the same problem and I solved it by changing the object data.file = e.target.file.files in the onSubmit as follows:
import React from "react";
import { Controller, useForm } from "react-hook-form";
import { Button, Form, Label, Input } from "reactstrap";
const App = () => {
const {
handleSubmit,
control,
setValue,
formState: { errors }
} = useForm();
const submitData = (data, e) => {
data.file = e.target.file.files
console.log(data);
};
return (
<div className="row">
<div className="col-sm-12 col-md-12 col-xl-12">
<Form onSubmit={handleSubmit(submitData)}>
<div className="row">
<div className="col-sm-6">
<Label for="file">File</Label>
<Controller
name="file"
control={control}
render={({ field }) => (
<Input {...field} type="file" id="file" />
)}
/>
</div>
</div>
<Button type="submit" color="primary">
Submit
</Button>
</Form>
</div>
</div>
);
};
export default App;

TypeError: Cannot read property 'validateFields' of undefined reactjs & django? how can i resolve this issue without antd?

when i try to login then i get this error (TypeError: Cannot read property 'validateFields' of undefined), i also read the documentation about antd but i don't want to use antd in my project how can i resolve this issue without antd... i have simple react-bootstrap Form... anybody know how can i solve this issue?
login.js
import React from 'react'
import { Link } from 'react-router-dom'
import { connect } from 'react-redux';
import { Form } from 'react-bootstrap';
import * as actions from './actions/auth';
import FullPageLoader from "../components/FullPageLoader";
class NormalLoginForm extends React.Component {
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
this.props.onAuth(values.userName, values.password);
this.props.history.push('/');
}
});
}
render() {
let errorMessage = null;
if (this.props.error) {
errorMessage = (
<p>{this.props.error.message}</p>
);
}
return (
<div className="form-flex">
{errorMessage}
{
this.props.isLoading ?
<FullPageLoader />
:
<Form onSubmit={this.handleSubmit} className="login-form form-group">
<h1 className="h4 text-center font-weight-normal">Sign in</h1>
<div className="form-group">
<input
className="form-control"
name="username"
autoComplete="off"
type="text"
required
placeholder="username" />
</div>
<div className="form-group">
<input
className="form-control"
name="password"
autoComplete="off"
type="password"
required
placeholder="password" />
</div>
<div className="form-group">
<button type="submit" className="btn btn-block btn-secondary">Login</button>
</div>
<small>
<Link to="/passwordforget">Forgot password?</Link>
</small>
</Form>
}
</div >
);
}
}
const mapStateToProps = (state) => {
return {
loading: state.loading,
error: state.error
}
}
const mapDispatchToProps = dispatch => {
return {
onAuth: (username, password) => dispatch(actions.authLogin(username, password))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(NormalLoginForm);
The error Cannot read property 'validateFields' of undefined is being caused by the code this.props.form.validateFields. You are not passing a form prop into the component so it is undefined, and throwing that error.
Either define a validator somewhere and use it, or remove that line.

Values with Redux-Form return null

im work with Redux and React, in CRUD operations with API , createPost return null into the values of title, categories, and content with Redux-Form?
I could help, I do not know what my mistake ?
actions file index.js
export const CREATE_POST = 'CREATE_POST';
const URL = 'http://reduxblog.herokuapp.com/api';
const API_KEY = '1234557';
export function createPost(props) {
const request = axios
.post(`${URL}/posts?${API_KEY}`, props)
.then( res => { console.log(res) })
return {
type: CREATE_POST,
payload: request,
};
}
component file newPost.js
import React from 'react';
import { reduxForm } from 'redux-form';
import {crearPost} from '../acciones/index';
import {connect} from 'react-redux';
class NuevoPost extends React.Component {
onSubmit(values) {
this.props.crearPost(values)
}
render() {
const {fields: {
title, categories, content} ,
handleSubmit } = this.props;
return (
<form onSubmit={
handleSubmit(this.onSubmit.bind(this))}>
<h3>Crea un nuevo Post.</h3>
<div className='form-group'>
<label
>titulo</label>
<input
type='text'
className='form-control'
{...title}
/>
</div>
<div className='form-group'>
<label
>Categoria</label>
<input
type='text'
className='form-control'
{...categories}
/>
</div>
<div className='form-group'>
<label
>Contenido</label>
<textarea
type='text'
className='form-control'
{...content}
/>
</div>
<button
type="submit"
className="btn btn-info"
>Postear</button>
</form>
)
}
}
export default reduxForm({
form: 'newPost',
fields: ['title', 'categories', 'content']
})(connect(null, { crearPost })(NuevoPost));
You need to use redux-form Field here
import { reduxForm, Field } from 'redux-form';
<div className='form-group'>
<label>Categoria</label>
<Field
type='text'
className='form-control'
component={'input'}
/>
</div>

Resources