Firebase stops saving when i use refresh - javascript

I want to refresh my page after save of newRider to Firebase. But when I use window.location.reload(); or with (false) it does not save. Without it it works.
And is it ok to have code that long in one file?
import React from "react";
import { RidersDB } from "../../Backend/DataBase/RidersDB";
const ridersDB = new RidersDB();
export default function CrewMemberSetCreate() {
const [newIsShown, setNewIsShown] = React.useState(false);
const [newRider, setNewRider] = React.useState({
firstName: "",
lastName: "",
age: 0,
favTrick: "",
dreamTrick: "",
youtube: "",
instagram: "",
isShown: newIsShown,
img: "",
});
function handleChange(event) {
setNewRider((prevNewRider) => {
return {
...prevNewRider,
[event.target.name]: event.target.value,
};
});
}
const createRider = (event) => {
event.preventDefault();
ridersDB.createRider({
firstName: newRider.firstName,
lastName: newRider.lastName,
age: Number(newRider.age),
favTrick: newRider.favTrick,
dreamTrick: newRider.dreamTrick,
youtube: newRider.youtube,
instagram: newRider.instagram,
isShown: newIsShown,
img: "",
});
//here i want reload and tried to usewindow.location.reload(false);
};
return (
<div className="setCreate">
<h2>Add Rider</h2>
<div className="centerForm">
<form>
<input
type="text"
placeholder="First Name"
onChange={handleChange}
value={newRider.firstName}
name="firstName"
/>
<input
type="text"
placeholder="Last Name"
onChange={handleChange}
value={newRider.lastName}
name="lastName"
/>
<input
type="number"
placeholder="Age (number)"
min="1"
onChange={handleChange}
value={newRider.age}
name="age"
/>
<input
type="text"
placeholder="Favourite Trick"
onChange={handleChange}
value={newRider.favTrick}
name="favTrick"
/>
<input
type="text"
placeholder="Dream Trick"
onChange={handleChange}
value={newRider.dreamTrick}
name="dreamTrick"
/>
<input
type="text"
placeholder="Youtube Link"
onChange={handleChange}
value={newRider.youtube}
name="youtube"
/>
<input
type="text"
placeholder="Instagram Link"
onChange={handleChange}
value={newRider.instagram}
name="instagram"
/>
<div className="checkboxDiv">
<label>Show on home page?</label>
<input
type="checkbox"
onClick={() => {
setNewIsShown((prevState) => !prevState);
}}
/>
</div>
<button onClick={createRider}>Add Rider</button>
</form>
</div>
</div>
);
}
RidersDB.js
import { db } from "./firebase-config";
import { addDoc, collection, getDocs } from "firebase/firestore";
export class RidersDB {
constructor() {
this.ridersCollRef = collection(db, "ridersCrew");
this.createRider = async (riderData) => {
await addDoc(this.ridersCollRef, riderData);
};
this.getRiders = async () => {
const data = await getDocs(this.ridersCollRef);
return data.docs.map((doc) => ({ ...doc.data(), id: doc.id }));
};
}
}

The createRider() methods returns a Promise. You should wait for it to resolve and then proceed. Try refactoring the code as shown below:
const createRider = (event) => {
event.preventDefault();
return ridersDB.createRider({
firstName: newRider.firstName,
// ....
}).then(() => {
// resolved, proceed now
window.location.reload(false)
}).catch((e) => console.log(e));
};

Related

File input always shows No file chosen

I'm building a form using React & Nodejs & MongoDB, where you can fill the form and upload a file with some other text inputs.
However, after i submit, i receive only text inputs in my database. The chosen file (desired to upload) doesn't appear at all in the database. I am expecting to get all the data form (the uploaded file and text inputed) in my database.
I tested my backend and it works correctly (it uploads all the inputs).
Ps: In browser, when i select a file (.pdf) to upload, the file input always shows no file chosen !
Console.dev : Error
{title: 'Miss', fname: 'zaezae', lname: 'zaeazee', email: 'zaea#mail.com', phoneNumber: '12345678', …}
coverLetter: "zaez e az ezae e zae aeae "
cv: ""
email: "zaea#mail.com"
fname: "zaezae"
lname: "zaeazee"
myFile: "C:\\fakepath\\test.pdf"
phoneNumber: "12345678"
title: "Miss"
Formulaire.jsx:29
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'then')
at submit (Formulaire.jsx:29:1)
Backend:
server.js:
const express = require('express')
const mongoose = require('mongoose')
const bodyparser = require('body-parser')
const FormRoute = require('./routes/FormRoute')
//database
mongoose.connect('mongodb://localhost:27017/form', { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (err) => {
console.log(err)
})
db.once('open', () => {
console.log("Database connection established!")
})
//app
const app = express()
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
//cors
const cors = require('cors')
app.use(cors())
//server run
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
app.use('/api/form', FormRoute);
Axios.js:
import axios from 'axios'
export const Axios = axios.create({
baseURL: 'http://localhost:5000',
})
Apiroutes.js:
const form = "/api/form"
export const requests = {
formApi: {
store: form + '/store'
}
}
formservices.js:
import { Axios } from "../config/axios";
import { requests } from "../config/apiroutes";
export const FormService = {
store: (data) => {
Axios.post(requests.formApi.store, data)
.then(res => {
return res
})
.catch(err => {
return err
})
}
}
formController.js :
const form = require('../models/FormModel')
const store = (req, res, next) => {
let candidate = new form({
title: req.body.title,
fname: req.body.fname,
lname: req.body.lname,
email: req.body.email,
phoneNumber: req.body.phoneNumber,
coverLetter: req.body.coverLetter
})
if (req.file) {
candidate.cv = req.file.path
}
candidate.save()
.then(response => {
res.json({
success: true,
message: 'Candidate added successfully!',
data: candidate,
})
})
.catch(error => {
res.json({
success: false,
message: 'An error occured!',
error: error,
})
})
}
module.exports = {
store
}
Frontend:
Formulaire.jsx :
import React, { useState } from 'react'
import Divider from '#mui/material/Divider';
import './Formulaire.css'
import { titles } from '../../mock/titles'
import { FormService } from '../../services/formServices';
const Form = () => {
const [storedata, setstoredata] = useState({
title: '',
fname: '',
lname: '',
email: '',
phoneNumber: '',
cv: '',
coverLetter: ''
})
const handleChange = e => {
const { name, value } = e.target;
setstoredata(prevState => ({
...prevState,
[name]: value
}));
};
const submit = async () => {
console.log(storedata);
await FormService.store(storedata)
.then(res => {
console.log(res);
})
.catch(err => {
return err
})
}
return (
<div className='container'>
<div className='header'>
<div className='title'>
<a className='quizbutton' href="/quiz">Take a Test (Quiz)</a>
<h1>Apply for a Position :</h1>
</div>
</div>
<Divider style={{ maxWidth: '1000px', marginLeft: '250px' }} />
<div id="content">
<div id="formWrapper">
<form id="msform" method='post' action='/uploadFile' enctype="multipart/form-data">
<fieldset id="fieldset3">
<h2 class="fs-title">Please complete the form below for a position with us.</h2>
<h3 class="fs-subtitle">Reference 0001</h3>
{/* <div class="fs-error"></div> */}
<div class="wrapper">
<label for="title">Title :</label>
<select name="title" value={storedata.title} onChange={handleChange}>
<option hidden></option>
{
titles.map((c, i) => {
return (
<option key={i} value={c}>{c}</option>
)
})
}
</select>
<label for="fname">First Name<span>*</span> :</label>
<input type="text" name="fname" value={storedata.fname} onChange={handleChange} id="fname" placeholder="Please enter your first name" required />
<label for="lname">Last Name<span>*</span> :</label>
<input type="text" name="lname" value={storedata.lname} onChange={handleChange} id="lname" placeholder="Please enter your last name" required />
<label for="email">Email<span>*</span> :</label>
<input type="email" name="email" value={storedata.email} onChange={handleChange} id="email" placeholder="Please enter your email" required />
<label for="phoneNumber">Phone N° :</label>
<input type="number" name="phoneNumber" value={storedata.phoneNumber} onChange={handleChange} id="phoneNumber" placeholder="Phone number" />
<label for="CV">Upload CV <span>*</span>:</label>
<input type="file" name="myFile" id="cv" value={storedata.cv} onChange={handleChange} accept="application/msword, application/pdf" placeholder="Cover Letter" required />
<label for="coverLetter">Cover Letter :</label>
<textarea type="text" name="coverLetter" value={storedata.coverLetter} onChange={handleChange} id="coverLetter" placeholder="cover Letter" />
</div>
<br />
<input type="submit" name="submit" class="submit action-button" value="Submit" onClick={submit} />
</fieldset>
</form>
</div>
</div>
</div>
)
}
export default Form
I fixed my problem by changing name="myFile" id="cv" to name="cv" id="cv"

How to post data to supabase through next.js

I currently have a simple next.js website where users can look at projects for an organization, and at the bottom of the page, the user can input a new project through the use of a form with multiple inputs. The database that i am currently using is Supabase.
My code currently takes in user input from each input box and stores them inside the newProject const, after which the data is then parsed into the createNewProject function and sent to Supabase.
const initialState = { solution_id: '', organization_id: '', budget_usd: '',other_info: '',country: '',project_duration_days: '',status: '',date_time_timezone: '' }
export default function Projects({ Projects }) {
useEffect(() => {
console.log(Projects)
}, [])
const [newProject, setProject] = useState(initialState)
console.log("User inputed data")
console.log(newProject)
const {solution_id, organization_id, budget_usd, other_info, country,project_duration_days,status,date_time_timezone} = newProject
const router = useRouter()
function onChange(e) {
setProject(() => ({ ...newProject, [e.target.name]: e.target.value }))
}
async function createNewProject() {
if (!solution_id || !organization_id || !country) return
const id = uuid()
newProject.id = id
const {data} = await supabase
.from('Projects')
.insert([
{ solution_id, organization_id, budget_usd,other_info,country,project_duration_days,status,date_time_timezone }
])
router.push(`/projects/${data.id}`)
}
return (
<div>
{Projects.map(project => {
return (
<div key={project.id}>
<h1><b>{project.Solutions.name} in {project.country}</b></h1>
<h2>Budget USD: {project.budget_usd}</h2>
<h2>Duration: {project.project_duration_days} days</h2>
<h2>Status: {project.status}</h2>
<h2>Organization: {project.Organizations.name}</h2>
<h2>Project Id: {project.id}</h2>
<button type="button" onClick={() => router.push(`/projects/${project.id}`)}>Donate now</button>
<br></br>
</div>
)
})}
<label htmlFor="solution_id ">solution_id</label>
<input onChange={onChange} value={newProject.solution_id} type="text" id="solution_id" name="solution_id" required />
<label htmlFor="organization_id ">organization_id</label>
<input onChange={onChange} value={newProject.organization_id} type="text" id="organization_id" name="organization_id" required />
<label htmlFor="budget_usd ">Last budget_usd</label>
<input onChange={onChange} value={newProject.budget_usd} type="text" id="budget_usd" name="budget_usd" required />
<label htmlFor="other_info ">other_info</label>
<input onChange={onChange} value={newProject.other_info} type="text" id="other_info" name="other_info" required />
<label htmlFor="country ">country</label>
<input onChange={onChange} value={newProject.country} type="text" id="country" name="country" required />
<label htmlFor="project_duration_days ">Project Duration Days</label>
<input onChange={onChange} value={newProject.project_duration_days} type="text" id="project_duration_days" name="project_duration_days" required />
<label htmlFor="status ">status</label>
<input onChange={onChange} value={newProject.status} type="text" id="status" name="status" required />
<label htmlFor="date_time_timezone ">date_time_timezone</label>
<input onChange={onChange} value={newProject.date_time_timezone} type="text" id="date_time_timezone" name="date_time_timezone" required />
<button type="button" onClick={createNewProject} >Submit new project</button>
</div>
)
}
export async function getServerSideProps() {
const fetchOrgs = async () => {
let { data: Organizations, error } = await supabase
.from('Organizations')
.select('*')
return Organizations
}
const fetchSolutions = async () => {
let { data: Solutions, error } = await supabase
.from('Solutions')
.select('*')
return Solutions
}
const fetchProjects = async () => {
let { data: Projects, error } = await supabase
.from('Projects')
.select(`
id,
solution_id,
organization_id,
budget_usd,
country,
project_duration_days,
status,
Solutions(name),
Organizations(name)
`)
.order('id', { ascending: true })
console.log(Projects)
return Projects
}
const Organizations = await fetchOrgs();
const Solutions = await fetchSolutions();
const Projects = await fetchProjects();
return { props: { Solutions, Organizations, Projects } }
}
However, whenever I press the submit button, the console.log for the newProject, would show that there is not data being passed into the variables, only the empty placeholder data in the initialState const. As such, I am unsure about how to pass data from next.js input forms into a variable to be posted into supabase.

Uncontrolled input React Hooks ( console error)

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
import React, { useEffect, useState } from 'react';
import axios from "axios"
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
function CreateExercise() {
const [createExercises, setExercise] = useState({
username: "",
description: "",
duration: 0,
date: new Date(),
users: []
});
useEffect(() => {
axios.get('http://localhost:5000/users/')
.then(response => {
if (response.data.length > 0) {
setExercise({
users: response.data.map(user => user.username),
username: response.data[0].username
})
}
})
}, [])
function handleChange(event) {
const { name, value } = event.target;
setExercise(prevExercise => {
return {
...prevExercise,
[name]: value
};
});
}
function changeDate(date) {
setExercise(prevExercise => {
return {
username: prevExercise.username,
description: prevExercise.description,
duration: prevExercise.duration,
date: date,
users: prevExercise.users
};
});
}
function onSubmit(event) {
event.preventDefault();
console.log(createExercises);
axios.post('http://localhost:5000/exercises/add', createExercises)
.then(res => console.log(res.data));
setExercise({
username: "",
description: "",
duration: 0,
date: new Date(),
users: []
});
window.location = '/';
}
return (
<div>
<h3>Create New Exercise log</h3>
<form >
<div>
<label>Username: </label>
<select
required
className="form-control"
value={createExercises.username}
onChange={handleChange}>
{
createExercises.users.map(function (user, index) {
return <option key={user} value={user}>{user}</option>;
})
}
</select>
</div>
<div className="form-group">
<label>Description: </label>
<input type="text"
name="description"
className="form-control"
onChange={handleChange}
value={createExercises.description}
/>
</div>
<div className="form-group">
<label>Duration (in minutes): </label>
<input type="text"
name="duration"
className="form-control"
onChange={handleChange}
value={createExercises.duration}
/>
</div>
<div className="form-group">
<label>Date: </label>
<DatePicker
selected={createExercises.date}
onChange={changeDate}
/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary" onClick={onSubmit} >Create Exercise Log</button>
</div>
</form>
</div>
);
}
export default CreateExercise;
how can i avoid above console error occured?
I think your problem is in your effect, particularly in the way you use setExercise, when you do:
setExercise({
users: response.data.map(user => user.username),
username: response.data[0].username
})
It doesn't "merge" (assign) the new data with previous state, what it does - is just sets the state, meaning your state object after this will be:
{ users:[], username:''}
So you actually lose description and other fields - hence the warning.
What you should do, is this:
setExercise((prevState) => ({
...prevState,
users: response.data.map(user => user.username),
username: response.data[0].username
}))

React. Transferring data from textarea to array JSON

I just started working with React and JSON and require some help. There is a textarea field in which a user enters some data. How to read row-wise the entered text as an array into a JSON variable of the request? Any assistance would be greatly appreciated.
The result I want is
{
id: 3,
name: 'Monika',
birthDay: '1999/01/01',
countryDTO: 'USA',
films: [
'Leon:The Professional',
'Star wars',
'Django Unchained',
],
} ```
My code:
import React from 'react';
import { Form, FormGroup, Label } from 'reactstrap';
import '../app.css';
export class EditActor extends React.Component {
state = {
id: '',
name: '',
birthDay: '',
countryDTO: '',
films: [],
}
componentDidMount() {
if (this.props.actor) {
const { name, birthDay, countryDTO, films } = this.props.actor
this.setState({ name, birthDay, countryDTO, films });
}
}
submitNew = e => {
alert("Actor added"),
e.preventDefault();
fetch('api/Actors', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: this.state.name,
birthDay: this.state.birthDay,
countryDTO: {
title: this.state.countryDTO
},
films: [{ title: this.state.films }]
})
})
.then(() => {
this.props.toggle();
})
.catch(err => console.log(err));
this.setState({
id: '',
name: '',
birthDay: '',
countryDTO: '',
films: ''
});
}
onChange = e => {
this.setState({ [e.target.name]: e.target.value })
}
render() {
return <div>
<table>
<tr>
<td colspan="2">
<h3> <b>Add actor</b></h3>
<FormGroup>
<Label for="id">Id: </Label>
<input type="text" name="id" onChange={this.onChange} value={this.state.id} /><p />
<Label for="name">Name:</Label>
<input type="text" name="name" onChange={this.onChange} value={this.state.name} /><p />
<Label for="birthDay">Birth day:</Label>
<input type="text" name="birthDay" onChange={this.onChange} value={this.state.birthDay} placeholder="1990/12/31" /><p />
<Label for="country">Country:</Label>
<input type="text" name="countryDTO" onChange={this.onChange} value={this.state.countryDTO} /><p />
<Label for="Films">Films:</Label>
<textarea name="films" value={this.state.films} onChange={this.onChange} /><p />
</FormGroup>
</td>
</tr>
<tr>
<td>
<Form onSubmit={this.submitNew}>
<button class="editButtn">Enter</button>
</Form>
</td>
</tr>
</table >
</div>;
}
}
export default EditActor;
If you change the below code it will work automatically.
State declaration
this.state = {
name: 'React',
films:["Palash","Kanti"]
};
Change in onechange function
onChange = e => {
console.log("values: ", e.target.value)
this.setState({ [e.target.name]: e.target.value.split(",") })
}
change in textarea
<textarea name="films" value={this.state.films.map(r=>r).join(",")} onChange={this.onChange} />
Code is here:
https://stackblitz.com/edit/react-3hrkme
You have to close textarea tag and the following code is :
<textarea name="films" value={this.state.films} onChange={this.onChange} >{this.state.films}</textarea>
My understanding of your problem is that you would like to have each line in the text area dynamically added as an entry in the films array. This can be achieved as follows:
import React, { Component } from "react";
export default class textAreaRowsInState extends Component {
constructor(props) {
super(props);
this.state = {
currentTextareaValue: "",
films: []
};
}
handleChange = e => {
const { films } = this.state;
const text = e.target.value;
if (e.key === "Enter") {
// Get last line of textarea and push into films array
const lastEl = text.split("\n").slice(-1)[0];
films.push(lastEl);
this.setState({ films });
} else {
this.setState({ currentTextareaValue: text });
}
};
render() {
const { currentTextareaValue } = this.state;
return (
<textarea
defaultValue={currentTextareaValue}
onKeyPress={this.handleChange}
/>
);
}
}
Keep in mind that this method is not perfect. For example, it will fail if you add a new line anywhere other than at the end of the textarea. You can view this solution in action here:
https://codesandbox.io/s/infallible-cdn-135du?fontsize=14&hidenavigation=1&theme=dark
change textarea() tag
to
<textarea name="films" value={this.state.films} onChange={this.onChange} >{this.state.films}</textarea>
You can use split() :
films: {this.state.films.split(",")}

not able to display material-ui dropdown with props values

I am trying to incorporate material-ui DropDown element into my page but I am getting map errors
My page code
import React, {Component} from 'react';
import {Button, Dropdown, Form} from 'semantic-ui-react'
import SimpleReactValidator from 'simple-react-validator';
import cookie from 'react-cookies'
import {Redirect} from 'react-router-dom'
const jsonData = require('../../../../../jsonData/data.json');
const dummyData = require('../../../../../jsonData/dummy.json');
import auth, {
axiosInst as axios,
removeElement,
addElement,
beforeSubmiteShaker,
afterSubmiteShaker
} from "../../../../helper";
import QuestionsFilters from '../../../../components/QuestionsFilters'
import DropDown from '../../../../components/ui/Select/Select'
const items = [
{value: 1, primaryText: 'Dhaval'},
{value: 2, primaryText: 'Dhavalu'},
{value: 3, primaryText: 'Dhavalaa'},
]
class RegisterCandidate extends Component {
constructor(props) {
super(props);
this.state = {
firstname: "",
lastname: "",
mobile_no: "",
email: "",
password: "",
city_id: "",
preference_list: [],
medium: "", //how did u find us
is_looking_for: "",
affiliate: "",
revert: "",
emailExist: "",
mobileExist: "",
isLogin: false,
historyRoute: "",
};
this.validator = new SimpleReactValidator();
}
componentDidMount() {
this.props.fetchCities()
this.props.fetchPreferences()
}
change(e) {
this.setState({
[e.target.name]: e.target.value
})
};
dropDownChange(e, {value, name}) {
this.setState({
[name]: value
})
}
emailcheck(e) {
if (this.validator.fieldValid('email')) {
let uri = '/email/exists';
axios.get(uri, {
params: {email: this.state.email}
})
.then((response) => {
this.setState({emailExist: response.data});
if (response.data.status != 'Failed') {
removeElement("p[id='serv-error email-exist']")
return axios.get('/droppedregistrations/add', {
params: {email: this.state.email}
}).then((response) => {
console.log("Email Dropped " + response.data)
}).catch((error) => {
console.log('failed')
})
} else {
removeElement("p[id='serv-error email-exist']")
addElement("#email", "serv-error email-exist", "This email already exists.")
}
})
.catch(error => {
console.log('error Email')
})
}
}
mobilecheck(e) {
if (this.state.mobile_no != isNaN && this.state.mobile_no.length == 10) {
let uri = '/number/exists';
axios.get(uri, {
params: {mobile_no: this.state.mobile_no}
}).then((response) => {
this.setState({mobile_noExist: response.data});
if (response.data.status != 'Failed') {
removeElement("p[id='serv-error mobile-exist']")
return axios.get('/droppedregistrations/add', {
params: {mobile_no: this.state.mobile_no}
}).then((response) => {
console.log("mobile dropped " + response.data)
}).catch((error) => {
console.log('failed')
})
} else {
removeElement("p[id='serv-error mobile-exist']")
addElement("#mobile_no", "serv-error mobile-exist", "This mobile already exists.")
}
})
.catch(error => {
console.log('You are experiencing slow internet please be patient and try again later')
})
}
}
addUserSubmit(e) {
e.preventDefault();
beforeSubmiteShaker("s_reg_submit", "shaker")
if (this.validator.allValid()) {
const userDetails = {//add data to a donstant to pot
firstname: this.state.firstname,
lastname: this.state.lastname,
email: this.state.email,
password: this.state.password,
mobile_no: this.state.mobile_no,
city_id: this.state.city_id,
medium: this.state.medium,
is_looking_for: this.state.is_looking_for,
preference_list: this.state.preference_list,
affiliate: this.state.affiliate
}
let uri = '/register/candidate';
axios.post(uri, userDetails)
.then((response) => {
this.setState({revert: response.data});
const gotBack = this.state.revert
if (gotBack.status === 'Success') {
cookie.remove('token')
cookie.save('token', gotBack.token, {path: '/'})
if (cookie.load('token')) {
this.setState({isLogin: true})
}
else {
console.log('Something went wrong while redirect.')
}
}
})
.catch(error => {
if (error.response.status === 422) {
afterSubmiteShaker("s_reg_submit", "shaker")
$.each(error.response.data.errors, function (index, value) {
var errorDiv = '#' + index;
$(errorDiv).after("<p id='serv-error' class='validation-message'>" + value + "</p>");
});
}
})
} else {
this.validator.showMessages();
this.forceUpdate();
afterSubmiteShaker("s_reg_submit", "shaker")
}
}
render() {
const {
firstname,
lastname,
mobile_no,
email,
password,
city_id,
preference_list,
medium,
is_looking_for,
affiliate,
isLogin
} = this.state;
//to get the items in level of education
let looking_for = jsonData.looking_for;
var looking_fors = []
for (let i = 0; i < looking_for.length; i++) {
looking_fors.push(looking_for[i]['value']);
}
if (isLogin) {
return <Redirect to='/register/candidate/step2'/>;
} else {
return (
<section className="container mt-3">
{/*one click register section*/}
<div className="row p-3">
<div className="col-md-6">
<div className="card text-center">
<div className="card-body">
<h3>Register Using</h3>
<br/>
<a href="/" className={"btn btn-block btn-lg btn-info"}> Register with Facebook</a>
<a href="/google/redirect" className={"btn btn-block btn-lg btn-danger"}> Register
with Google</a>
<br/>
</div>
</div>
</div>
{/*end of one click register section*/}
{/*manuel register section*/}
<div className="col-md-6">
<div id="shaker" className="card">
<div className="card-body">
<h5 className="card-title">Register Candidate</h5>
<Form onSubmit={this.addUserSubmit.bind(this)}>
<Form.Field>
<label>First Name*</label>
<input name="firstname" id="firstname" value={firstname}
onChange={e => this.change(e)} type="text"
placeholder='Enter First Name*'/>
{this.validator.message('first name', firstname, 'required|alpha')}
</Form.Field>
<Form.Field>
<label>Last Name*</label>
<input name="lastname" id="lastname" value={lastname}
onChange={e => this.change(e)} type="text"
placeholder='Enter Last Name'/>
{this.validator.message('last name', lastname, 'required|alpha')}
</Form.Field>
<Form.Field>
<label>Mobile No*</label>
<input name="mobile_no" id="mobile_no" value={mobile_no}
onBlur={this.mobilecheck.bind(this)} onChange={e => this.change(e)}
type="text" placeholder='Enter mobile_no'/>
{this.validator.message('mobile no.', mobile_no, 'required|phone|min:10|max:10')}
</Form.Field>
<Form.Field>
<label>Email*</label>
<input name="email" id="email" value={email}
onBlur={this.emailcheck.bind(this)} onChange={e => this.change(e)}
type="text" placeholder='Enter Email'/>
{this.validator.message('email', email, 'required|email')}
</Form.Field>
<Form.Field>
<label>Password*</label>
<input name="password" id="password" value={password}
onChange={e => this.change(e)} type="password"
placeholder='Enter Password'/>
{this.validator.message('password', password, 'required|min:6')}
</Form.Field>
<Form.Field>
<label>City*</label>
<Dropdown placeholder='Select City' id="city_id" name="city_id" search
selection options={this.props.city_opt} value={city_id}
onChange={this.dropDownChange.bind(this)}/>
{this.validator.message('city', city_id, 'required|gt:0')}
</Form.Field>
<Form.Field>
<label>Preference*</label>
<Dropdown placeholder='Select Preference' id="preference_list"
name="preference_list" search multiple selection
options={this.props.preference_list_opt} value={preference_list}
onChange={this.dropDownChange.bind(this)}/>
{this.validator.message('preference', preference_list, 'required|max:3', false, {max: 'Maximum 3 preferences allowed'})}
</Form.Field>
<Form.Field>
<label>How did you find us?*</label>
<Dropdown placeholder='Please Select' id="medium" name="medium" search
selection options={jsonData.medium} value={medium}
onChange={this.dropDownChange.bind(this)}/>
{this.validator.message('medium', medium, 'required')}
</Form.Field>
<Form.Field>
<label>What are you looking for?*</label>
<Dropdown placeholder='Please Select' id="is_looking_for"
name="is_looking_for" search selection
options={jsonData.looking_for} value={is_looking_for}
onChange={this.dropDownChange.bind(this)}/>
{this.validator.message('', is_looking_for, 'required|in:' + looking_fors)}
</Form.Field>
<Form.Field>
<label>affiliate Code</label>
<input name="affiliate" value={affiliate} onChange={e => this.change(e)}
type="text" placeholder='Enter preference_list'/>
</Form.Field>
<Button id="s_reg_submit" className={"btn btn-block btn-lg"}
type='submit'>Submit</Button>
</Form>
<QuestionsFilters/>
</div>
</div>
</div>
{/*end of manuel register section*/}
<DropDown items={items}/>
</div>
</section>
)
}
}
}
export default RegisterCandidate;
my DropDown component code
import React, {Component} from 'react';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
const styles = {
customWidth: {
width: 200,
},
};
class DropDownMenuSimpleExample extends Component {
constructor(props) {
super(props);
this.state = {value: 1, items: ['abcd', 'efgh']};
}
handleChange(event, index, value) {
return this.setState({value})
}
render() {
let propItems = this.props.items
return (
<DropDownMenu
value={this.state.value}
onChange={this.handleChange.bind(this)}
style={styles.customWidth}
autoWidth={false}
>
{(propItems !== null || propItems != 'undefined' ) ? (propItems).map((item, index) => <MenuItem key={index} value={1}
primaryText="Custom height"/>) : (this.state.items).map((item, index) =>
<MenuItem key={index} value={1} primaryText="Custom width"/>)}
</DropDownMenu>
);
}
}
export default DropDownMenuSimpleExample
it is telling me that It cannot call map on null and in the first render the value of props shows undefined but then it is defined so not able to get to render the DropDown element properly..
any help will be highly appreciated
Please Note :- with just the state I get the proper dropdown but the issue happens only when I am passing props as data for the dropdown

Categories