Add parameter at onClose in relation Modal - react-hooks

Goal:
When you press the button named "yes 1", the value should contain "yes yes" and in the end the console.log should display "test yes yes".
When you press the button named "yes 2", the value should contain "no no" and in the end the console.log should display "test no no".
The display of the value "test yes yes" or "test no no" take place at index.tsx.
The execution or the decision take place at ModalForm.tsx.
Problem:
In technical perspectiv, tried to find a solution by using this code onClick={props.onClose("yes yes")} but it doesn't work.
How do I solve this case?
Stackblitz:
https://stackblitz.com/edit/react-ts-rpltpq
Thank you!
index.html
<div id="root"></div>
<!-- Latest compiled and minified CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
index.tsx
import React, { Component, useState, useEffect } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import { ModalForm } from './ModalForm';
import './style.css';
interface dddd {
clientid: string | undefined;
idid: number;
}
const getTest = () => {
console.log('test');
};
const App = () => {
const [clientiddd, setClientid] = useState('ddfdf');
const [idid, setIdid] = useState(0);
return (
<div>
<button
data-bs-toggle="modal"
data-bs-target="#myModalll"
className={'btn btn-outline-dark'}
>
{'data'}
</button>
<br />
<ModalForm clientid={clientiddd} onClose={getTest} />
</div>
);
};
render(<App />, document.getElementById('root'));
ModalForm.tsx
import React, { Component } from 'react';
interface ModalProps {
clientid: string | undefined;
onClose: () => void;
}
export const ModalForm = (props: ModalProps) => {
return (
<div
className="modal"
id="myModalll"
data-bs-backdrop="static"
data-bs-keyboard="false"
tabIndex={-1}
aria-labelledby="staticBackdropLabel"
aria-hidden="true"
>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h4 className="modal-title">T</h4>
<button
type="button"
className="btn-close btn-close-black"
data-bs-dismiss="modal"
onClick={props.onClose}
></button>
</div>
<div className="modal-body">
TITLE:
<br />
<button
type="button"
data-bs-dismiss="modal"
onClick={props.onClose}
>
yes 1
</button>
<button
type="button"
data-bs-dismiss="modal"
onClick={props.onClose}
>
yes 2
</button>
<br />
</div>
</div>
</div>
</div>
);
};

It's somewhat hard to understand your question, but let me try.
onClick={props.onClose('yes yes')}
What this code does is that it calls props.onClick with yes yes as an argument and assigns the returned value as the onClick listener.
Assume the props.onClose is this:
function onClose() {
console.log('test')
}
What it does here is that it calls this function (it logs test to the console) but since this function is not returning anything, it passes undefined as the onClick here.
If instead your function was this:
function onClose(result) {
return function () {
console.log('test', result)
}
}
Now it would call props.onClose with yes yes and it would return a function. This anonymous function would be passed as the onClick event listener and when you click, it would call that so there would be test yes yes logged only after clicking.
You can as well do it differently, keep your onClose function as it was but introduce result:
function onClose(result) {
console.log('test', result)
}
but now you have to pass this function instead of calling it:
onClick={() => props.onClose('yes yes')}
As you can see, there will always be one anonymous function somewhere in there, it's just a question of where that function is and what is called when. Hope this explanation helps.

https://stackblitz.com/edit/react-ts-nw6upt?file=index.html
index.html
<div id="root"></div>
<!-- Latest compiled and minified CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
index.tsx
import React, { Component, useState, useEffect } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import { ModalForm } from './ModalForm';
interface dddd {
clientid: string | undefined;
idid: number;
}
const getTest = (result: string) => {
console.log('testff ' + result);
};
const App = () => {
const [clientiddd, setClientid] = useState('ddfdf');
const [idid, setIdid] = useState(0);
return (
<div>
<button
data-bs-toggle="modal"
data-bs-target="#myModalll"
className={'btn btn-outline-dark'}
>
{'data'}
</button>
<br />
<ModalForm clientid={clientiddd} onClose={getTest} />
</div>
);
};
render(<App />, document.getElementById('root'));
ModalForm.tsx
import React, { Component } from 'react';
interface ModalProps {
clientid: string | undefined;
onClose: (result: string) => void;
}
export const ModalForm = (props: ModalProps) => {
return (
<div
className="modal"
id="myModalll"
data-bs-backdrop="static"
data-bs-keyboard="false"
tabIndex={-1}
aria-labelledby="staticBackdropLabel"
aria-hidden="true"
>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h4 className="modal-title">T</h4>
<button
type="button"
className="btn-close btn-close-black"
data-bs-dismiss="modal"
onClick={() => props.onClose('ccc')}
></button>
</div>
<div className="modal-body">
TITLE:
<br />
<button
type="button"
data-bs-dismiss="modal"
onClick={() => props.onClose('aaa')}
>
yes 1
</button>
<button
type="button"
data-bs-dismiss="modal"
onClick={() => props.onClose('bbb')}
>
yes 2
</button>
<br />
</div>
</div>
</div>
</div>
);
};

Related

How to show/hide #foreach statement

I have a Vuejs 3 dropdown reusable component. My problem is that the #foreach statement runs before the component loads so it causes a flash of the foreach results which is very ugly upon refresh or when the page is loading.
To demonstrate please check this gif:
My component in blade:
<Dropdown title="{{ isset($currentCategory) ? ucwords($currentCategory->name) : 'Categories' }}">
<Dropdowncontent>
<Dropdownitems href="/">
All
</Dropdownitems>
<div>
#foreach ($categories as $category)
<Dropdownitems
href="/?category={{ $category->slug }}&{{ http_build_query(request()->except('category')) }}"
class="{{ isset($currentCategory) && $currentCategory->is($category) ? ' selectedCategoryItem' : '' }}">
{{ $category->name }}
</Dropdownitems>
#endforeach
</div>
</Dropdowncontent>
</Dropdown>
I added a div to contain the #foreach statement but i don't know what to do from here. I don't want to use alpineJS as it will defeat the purpose of using Vue (I guess?).
I just need a way to only display this div or the #foreach statement if the component is fully loaded or if the button is pressed or something like that. Any ideas?
-- EDIT --
I tried to hide the links in my 'dropdownitems' vue component and set the default value to false. The links are now hidden but still the blade #foreach statement echoing out the results as text before the component is loaded:
<template>
<a v-if="showLinks" href="" class="demogard categoryItems">
<slot />
</a>
</template>
<script>
export default {
name: "Dropdownitems",
setup() {
const showLinks = false;
return {
showLinks,
};
},
};
</script>
<style></style>
Here is a gif to show the result of that:
-- EDIT --
Here is my dropdown component:
<template>
<div
class="relative"
v-click-outside="onClickOutside"
#click="showCategories"
>
<slot name="toggler">
<button
class="flex max-h-52 w-full overflow-auto py-2 pl-3 pr-9 text-sm font-semibold lg:inline-flex lg:w-32"
>
{{ title }}
</button>
</slot>
<slot />
</div>
</template>
<script>
import vClickOutside from "click-outside-vue3";
import { ref, onMounted, provide } from "vue";
export default {
name: "Dropdown",
props: ["title"],
directives: {
clickOutside: vClickOutside.directive,
},
setup() {
const sharedState = ref(false);
const showCategories = () => {
sharedState.value = !sharedState.value;
};
const onClickOutside = (event) => {
sharedState.value = false;
};
provide("sharedState", sharedState);
return {
sharedState,
showCategories,
onClickOutside,
};
},
};
</script>
<style></style>
As your question, I think you have to add if condition on your dropdown component.
Your dropdown component should be like this
#dropdown.vue
<template>
<div class="dropdown">
<div #click="show = !show">{{title}}</div>
<div v-if="show">
<slot />
</div>
</div>
</template>
<script>
import { ref } from "vue";
export default {
props: ["title"],
setup(props) {
const show = ref(false);
return {
show,
};
},
};
</script>
Demo
---- EDIT ----
#dropdown.vue
<template>
<div
class="relative"
v-click-outside="sharedState = false"
>
<slot name="toggler">
<button
class="flex max-h-52 w-full overflow-auto py-2 pl-3 pr-9 text-sm font-semibold lg:inline-flex lg:w-32"
#click="sharedState = !sharedState"
>
{{ title }}
</button>
</slot>
<div v-if="sharedState">
<slot />
</div>
</div>
</template>
<script>
import vClickOutside from "click-outside-vue3";
import { ref, onMounted, provide } from "vue";
export default {
name: "Dropdown",
props: ["title"],
directives: {
clickOutside: vClickOutside.directive,
},
setup() {
const sharedState = ref(false);
// const showCategories = () => {
// sharedState.value = !sharedState.value;
// };
// const onClickOutside = (event) => {
// sharedState.value = false;
// };
provide("sharedState", sharedState);
return {
sharedState,
//showCategories,
//onClickOutside,
};
},
};
</script>
<style></style>
Try with a #if directive:
Conditional Rendering
from the documentation:
<button #click="awesome = !awesome">Toggle</button>
<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no 😢</h1>
As showed in the example it render the "h1" tag conditionally respect the "awesome" variable.
In this case i will set a default value of "false" and i will turn it to "true" in the mounted hook:
Lifecycle
It's impossible to load Vue before PHP because your webpage only displays when full PHP code is received from the server. Therefore, we're never able to stop PHP or HTML from flashing if we're using them inside a reusable Vue component.
The solution I made is simply passing the value of the foreach loop as a prop to the Vue component in order for it to be displayed from there, not from my blade file.
Here's my code in blade after passing the value of the category name as a prop to my Vue component.
<Dropdown title="{{ isset($currentCategory) ? ucwords($currentCategory->name) : 'Categories' }}">
<Dropdowncontent>
<Dropdownitems href="/" category="All"></Dropdownitems>
#foreach ($categories as $category)
<Dropdownitems
category="{{ $category->name }}"
href="/?category={{ $category->slug }}&{{ http_build_query(request()->except('category')) }}"
class="{{ isset($currentCategory) && $currentCategory->is($category) ? ' selectedCategoryItem' : '' }}">
</Dropdownitems>
#endforeach
</Dropdowncontent>
</Dropdown>
Here is me displaying it from there the Vue dropdown items component:
<template>
<a href="" class="demogard categoryItems">
<slot>{{ category }}</slot>
</a>
</template>
<script>
export default {
name: "Dropdownitems",
props: ["category"],
};
</script>
<style></style>

React JS: How to call a function to return JSX code?

I'm new to react and I'm trying to create a JSX element in a function. The JSX should dynamically add 2 buttons each time when you click the button. However, when render() calls this function, it isn't rendering the element (white page in browser).
How would I go about fixing this? Any help would be appreciated. Thanks!
class Test extends Component {
constructor(){
super();
this.state = {
fields: [{key:'key', val:'val'}]
}
this.renderPanel = this.renderPanel.bind(this);
}
addField() {
this.setState({
fields: [...this.state.fields, {key:'key', val:'val'}],
})
}
renderPanel(){
return <div>
<form>
<div id="testingAPanel">
{()=>this.state.fields.map((input,index) => {return(
<tr>
<input type='button' id={index} value={input.key} />
<input type='button' id={index} value={input.val} />
<br/>
</tr>
)}
)}
</div>
</form>
<button onClick={ () => this.addField() }>
CLICK ME TO ADD AN INPUT
</button>
</div>
}
render() {
return (
<div class = 'test'>
{()=>this.renderPanel()}
</div>
);
}
}
export default Test;```
class App extends React.Component {
buttonClick(){
console.log("came here")
}
subComponent() {
return (<div>Hello World</div>);
}
render() {
return (
<div className="patient-container">
<button onClick={this.buttonClick.bind(this)}>Click me</button>
{this.subComponent()}
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
it depends on your need, u can use either this.renderIcon() or bind this.renderIcon.bind(this)
UPDATE
This is how you call a method outside the render.
buttonClick(){
console.log("came here")
}
render() {
return (
<div className="patient-container">
<button onClick={this.buttonClick.bind(this)}>Click me</button>
</div>
);
}
The recommended way is to write a separate component and import it.

Called React-Redux action in prop does not give needed results

I am implementing a component that handles an redux action to add comments but it is not working.No error is generated
I have tried calling the props from other regions in the code but that doesnt seem to work.The addComment Action should add the comments rendered in the DishDetails comments section.However no additions are made.
ActionTypes.js
export const ADD_COMMENT='ADD_COMMENT';
ActionCreators.js
import * as ActionTypes from './ActionTypes';
export const addComment=(dishId,rating, author, comment)=>({
type: ActionTypes.ADD_COMMENT,
payload: {
dishId:dishId,
rating:rating,
author:author,
comment:comment
}
});
comments.js
import { COMMENTS } from '../shared/comments';
import * as ActionTypes from './ActionTypes';
export const Comments= (state= COMMENTS, action) => {
switch(action.type){
case ActionTypes.ADD_COMMENT:
var comment= action.payload;
comment.id= state.length;
comment.date = new Date().toISOString();
return state.concat(comment);
default:
return state;
}
};
MainComponent.js
import React, { Component } from 'react';
import Header from './HeaderComponent';
import Footer from './FooterComponent';
import Menu from './MenuComponent';
import DishDetail from './DishDetail';
import Home from './HomeComponent';
import { Switch, Route, Redirect, withRouter } from 'react-router-dom';
import Contact from './ContactComponent';
import About from './AboutComponent';
import { connect } from 'react-redux';
import {addComment} from '../redux/ActionCreators';
const mapStateToProps = state =>{
return{
dishes: state.dishes,
comments: state.comments,
promotions: state.promotions,
leaders: state.leaders
}
};
const mapDispatchToProps = dispatch => ({
addComment: (dishId,rating, author, comment)=>dispatch(addComment(dishId,rating, author, comment))
});
class Main extends Component {
constructor(props) {
super(props);
}
render() {
const HomePage= ()=>{
return(
<Home dish={this.props.dishes.filter((dish)=>dish.featured)[0]}
promotion={this.props.promotions.filter((promotion)=>promotion.featured)[0]}
leader={this.props.leaders.filter((leader)=>leader.featured)[0]}
/>
);
}
const DishWithId = ({match})=>{
return(
<DishDetail dish={this.props.dishes.filter((dish)=>dish.id === parseInt(match.params.dishId,10))[0]}
comments={this.props.comments.filter((comment)=>comment.dishId=== parseInt(match.params.dishId,10))}
addComment={this.props.addComment}/>
);
}
const AboutPage = ()=>{
return(
<About leaders={this.props.leaders}/>
);
}
return (
<div>
<Header/>
<Switch>
<Route path="/home" component={HomePage} />
<Route exact path="/menu" component={()=><Menu dishes ={this.props.dishes} />} />
<Route path="/menu/:dishId" component={DishWithId}/>
<Route exact path="/aboutus" component={() => <AboutPage leaders={this.props.leaders} />} />}/>
<Route exact path="/contactus" component={Contact}/>
<Redirect to="/home"/>
</Switch>
<Footer/>
</div>
);
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Main));
DishDetail.js
import React, { Component } from 'react';
import { Card, CardImg, CardImgOverlay, CardText, CardBody, CardTitle, Breadcrumb, BreadcrumbItem , Button, Modal, ModalHeader,ModalBody, Form, FormGroup, Input, Label, Col, Row } from 'reactstrap';
import {Control, LocalForm, Errors} from 'react-redux-form';
import {Link} from 'react-router-dom';
const required = (val) =>val && val.length;
const maxLength = (len) => (val) => !(val) || (val.length <= len);
const minLength = (len) => (val) => val && (val.length >= len);
class DishDetail extends Component{
constructor(props){
super(props);
this.state={
dish:props.dish,
isCommentModalOpen: false,
};
this.toggleCommentModal=this.toggleCommentModal.bind(this);
}
toggleCommentModal(){
this.setState({
isCommentModalOpen:!this.state.isCommentModalOpen
});
}
handleSubmit(props,values){
alert("State" + JSON.stringify(props.addComment(props.dishId, values.rating, values.author, values.comment)));
// this.state.addComment(this.state.dishId, values.rating, values.author, values.comment)
}
render(){
const RenderDish=({dish})=>{
return(
<Card>
<CardImg top src={dish.image} alt={dish.name}/>
<CardBody>
<CardTitle>{dish.name}</CardTitle>
<CardText>{dish.description}</CardText>
</CardBody>
</Card>
);
}
const RenderComments=({comments})=>{
const comment_layout= comments.map((comment)=>{
if(comment.comment!=null){
return(
<div>
{comment.comment}
{comment.author}, {new Intl.DateTimeFormat('en-US',{year:'numeric',month:'short',day:'2-digit'}).format(new Date(Date.parse(comment.date)))}
</div>
);
}else{
return(
<div></div>
);
}
});
return(comment_layout);
}
const CommentForm=()=>{
return(
<Button outline onClick={this.toggleCommentModal}>
<span className="fa fa-edit fa-lg">Submit Comment</span>
</Button>
);
}
if (this.state.dish!==undefined){
return (
<div className="container">
<div className="row">
<Breadcrumb>
<BreadcrumbItem>
<Link to="/menu">Menu</Link>
</BreadcrumbItem>
<BreadcrumbItem active>{this.state.dish.name}
</BreadcrumbItem>
</Breadcrumb>
<div className="col-12">
<h3>{this.state.dish.name}</h3>
<hr/>
</div>
</div>
<div className="row ">
<div className="col-12 col-md-5 m-1">
<RenderDish dish={this.state.dish}/>
</div>
<div className="col-md-5 col-sm-12 m-1">
<h4>Comment</h4>
<RenderComments comments={this.props.comments}
/>
<CommentForm/>
</div>
</div>
<Modal isOpen={this.state.isCommentModalOpen} toggle={this.toggleCommentModal}>
<ModalHeader toggle={this.toggleCommentModal}>
Submit Comment </ModalHeader>
<ModalBody>
<div className="col-12">
<LocalForm onSubmit={(values)=>this.handleSubmit(this.props,values)}>
<Row className="form-group">
<Label htmlFor ="rating" md={2}>Rating</Label>
<Control.select model=".rating" id="rating" name="rating" className="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</Control.select>
</Row>
<Row className="form-group">
<Label htmlFor ="name" md={2}>Name</Label>
<Control.text model=".name" className="form-control" id="name" name="name" placeholder="name" validators={{required,minLength: minLength(3),maxLength:maxLength(15)}} />
<Errors className="text-danger"
model=".name"
show="touched"
messages={{
required:'Required',
minLength:'Must be greater than 2 char',
maxLength: 'Must be 15 chars or less'
}}
/>
</Row>
<Row className="form-group">
<Label htmlFor ="feedback" md={2}>Comment</Label>
<Control.textarea model=".message" className="form-control" id="message" name="message" rows="12" />
</Row>
<Row className="form-group">
<Button type="submit" color="primary">
Submit
</Button>
</Row>
</LocalForm>
</div>
</ModalBody>
</Modal>
</div>
);
}else{
return(
<div></div>
);
}
}
}
export default DishDetail;
you are not dispatching to the reducer in the action. Do it like this
export const addComment = (dishId, rating, author, comment) => {
return (dispatch) => {
dispatch({
type: ActionTypes.ADD_COMMENT,
payload: {
dishId: dishId,
rating: rating,
author: author,
comment: comment
}
})
}
};

Unit test case for React Component using enzyme

I am working on reactjs 5.X version. I am writing UT with enzyme. Below is my reusable component with prop arguments. Not able to find the div tags inside of the const component.Can you help me how to get the div tags using classname or using find function to get div tags.
import React from 'react';
import styles from './democheck.css';
const democheck = ({ input, cb,
required, testCheckbox, checked, label, meta: { error } }) => (
<div id="hierrdivid" className={styles.testDivColumn}>
<div className={styles.testDiv}>
<br />
<span className={styles.testLabel}>
{label}
</span>
{required && <span className={styles.error}>
*
</span>}
<input
{...input}
name={`form-field-${input.name}`}
checked={checked}
id={input.name}
className={testCheckbox ? styles.testCheckboxError :
styles.testCheckbox}
type="checkbox"
onChange={() => {
if (cb) {
cb(document.getElementById(input.name).checked);
}
}}
/>
</div>
<div className={styles.testerrorDiv}>
{testCheckbox &&
<div className={styles.testerrorLabel}>
{label} {error}
</div>}
</div>
</div>
);
democheck.propTypes = {
input: React.PropTypes.objectOf(React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.func
])),
cb: React.PropTypes.func,
label: React.PropTypes.string,
meta: React.PropTypes.shape({}),`enter code here`
required: React.PropTypes.bool,
checked: React.PropTypes.bool,`enter code here`
testCheckbox: React.PropTypes.bool
};

redux-form data is not passed to handleSubmit

I'm having trouble again with redux-form. I'm calling the handleSubmit function from the parent, and the windows.alert() is calledcorrectly, but the data is not passed to the function. What am I doing wrong?
import React, {Component, PropTypes} from 'react';
import {reduxForm} from 'redux-form';
import memberValidation from './memberValidation';
class DashboardAdding extends Component {
static propTypes = {
fields: PropTypes.object.isRequired,
handleSubmit: PropTypes.func.isRequired,
resetForm: PropTypes.func.isRequired
}
render() {
const {
fields: { pseudo, email},
handleSubmit,
resetForm
} = this.props;
return (
<div>
<form className="form-horizontal" onSubmit={handleSubmit.bind(this)}>
<div className={'form-group' + (pseudo.error && pseudo.touched ? ' has-error' : '')}>
<label className="col-sm-2">Pseudo</label>
<div className={'col-sm-8 '}>
<input type="text" className="form-control" id="pseudo" {...pseudo}/>
{pseudo.error && pseudo.touched && <div className="text-danger">{pseudo.error}</div>}
</div>
</div>
<div className={'form-group' + (email.error && email.touched ? ' has-error' : '')}>
<label className="col-sm-2">Email</label>
<div className={'col-sm-8 '}>
<input type="text" className="form-control" id="email" {...email}/>
{email.error && email.touched && <div className="text-danger">{email.error}</div>}
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button className="btn btn-success" onClick={handleSubmit}>
<i className="fa fa-paper-plane"/> Submit
</button>
<button className="btn btn-warning" onClick={resetForm} style={{marginLeft: 15}}>
<i className="fa fa-undo"/> Reset
</button>
</div>
</div>
</form>
</div>
);
}
}
export default reduxForm({
form: 'dashboardForm',
fields: ['pseudo', 'email'],
validate: memberValidation,
asyncBlurFields: ['email']
})(DashboardAdding);
...and the parent calling the handleSubmit:
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import Helmet from 'react-helmet';
import {bindActionCreators} from 'redux';
import {initialize} from 'redux-form';
import {isLoaded, loadMembers} from 'redux/modules/members/members';
import * as addActions from 'redux/modules/members/addSingleMember';
import {addMember} from 'redux/modules/members/addSingleMember';
import { DashboardList } from 'components';
import { DashboardHeader } from 'components';
import { DashboardAdding } from 'components';
import { asyncConnect } from 'redux-async-connect';
#asyncConnect([{
deferred: true,
promise: ({store: {dispatch, getState}}) => {
if (!isLoaded(getState())) {
return dispatch(loadMembers());
}
}
}])
class Dashboard extends Component {
static propTypes = {
members: PropTypes.array,
error: PropTypes.string,
loading: PropTypes.bool,
addMember: PropTypes.func,
initialize: PropTypes.func.isRequired
}
handleSubmit = (data, dispatch) => {
window.alert(data);
dispatch(addMember(JSON.stringify(data)));
this.props.initialize('dashboardForm', {});
}
handleInitialize = () => {
this.props.initialize('dashboardForm', {
pseudo: 'Pibo',
email: 'pibirino#gmail.com'
});
}
render() {
const {members} = this.props;
return (
<div className="container">
<h1>Dashboard</h1>
<Helmet title="Dashboard"/>
<DashboardHeader />
<div>
<DashboardList members={members}/>
<h3>Ici commence le form</h3>
<div style={{textAlign: 'center', margin: 15}}>
<button className="btn btn-primary" onClick={this.handleInitialize}>
<i className="fa fa-pencil"/> Initialize Form
</button>
</div>
</div>
<DashboardAdding onSubmit={this.handleSubmit}/>
</div>
);
}
}
function mapStateToProps(state) {
return {
members: state.members.data,
error: state.members.error,
loading: state.members.loading
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({
addActions,
addMember,
initialize: initialize
}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(Dashboard);
The redux-documentation says:
"You are upgrading from a previous version of redux-form that required that {valid: true} be returned".
I suspect that the problem is that, but I really don't understand what that could mean!
My version -> "redux-form": "^3.0.0"
Thanks!
Find the solution where I didn't expect... The form gives the data in json format. JSON.stringify() messed it up.
I hope it can help somebody. Bye

Resources