InitialValues aren't populating redux form - redux

At the moment, I'm having difficulty populating the input fields for a redux form with initial values. Could someone please tell me what's wrong with the following code, or if this is a known issue? Thanks for the help and support.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm, reset, initialize } from 'redux-form'
const renderField = props => (
<div>
<label>{props.placeholder}</label>
<div>
<input {...props}/>
{props.touched && props.error && <span>{props.error}</span>}
</div>
</div>
)
class EditArtist extends Component {
render() {
const { initialValues} = this.props;
console.log(initialValues)
return (
<form>
<Field name="name" component={renderField} type="text" placeholder="Name"/>
</form>
)
}
}
const validate = values => {
const errors = {};
return errors;
}
const mapStateToProps = (state) => ({
initialValues: {
name: "COOL"
}
});
export default connect(mapStateToProps)(reduxForm({
form: 'edit_artist_form',
validate,
enableReinitialize: true
})(EditArtist));

Related

How can I mix between a ssr component and a client component in Nextjs 13?

The point is to implement a dynamic SSR component can be re-rendered by a search input.
I solved this by creating a layout.tsx file on my specific router then import children which made me dynamic render ssr component by the client component:
Layout.tsx
import React, { Suspense } from "react";
import Search from "./Search";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="layout">
<Search />
{children}
</div>
);
}
Search.tsx
"use client";
import { FormEvent, useState } from "react";
import { useRouter } from "next/navigation";
export default function Search() {
const [text, setText] = useState<string>("")
const router: any = useRouter();
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
setText('')
router.push(`/definition/${text}`)
}
return (
<form onSubmit={handleSubmit} className='search'>
<input onChange={(e) => setText(e.target.value)}
value={text} type="text"
placeholder={"write to search"} />
</form>
);
} );
}

Story with its own states and methods

To demonstrate a component I try to write custom state and methods for a story.
For example, I have a component ListItems who accepts an array of string as Input.
In the story of this component I want to show an interactive example of the usage of this component.
So my story will have internal state "items" and internal method "addItem"
I know how to do that with React, but I'm stuck with Angular.
Here is a React way to do that:
(View in codesandbox)
// ListItems.tsx
import React from "react";
export type ListItemsProps = { items: string[] };
export const ListItems = ({ items = [] }: ListItemsProps) => {
return (
<ul>
{items.map((item, key) => (
<li key={key}>{item}</li>
))}
</ul>
);
};
// ListItems.stories.tsx
import React, { useState } from "react";
import { ListItems } from "./ListItems";
export default {
title: "ListItems",
component: ListItems
};
export const Text = () => {
const [items, setItems] = useState(["Demo Item"]);
const [value, setValue] = useState("");
const addItem = () => {
setItems([...items, value]);
setValue("");
};
return (
<div>
<ListItems items={items} />
<input value={value} onChange={(e) => setValue(e.target.value)} />
<input type="submit" onClick={addItem} value="add" />
</div>
);
};
};
How can I write the same story with following Angular Component ?
import { Component, OnInit, Input } from "#angular/core";
#Component({
selector: "app-list-items",
template: `<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>`
})
export default class ListItems implements OnInit {
#Input() items: string[] = [];
constructor(){}
ngOnInit(): void {}
}
Finally I found a solution on Angular, but it's not an elegant one...
Maybe someone know a better way !
And I can't find a solution to show the code story template on "Show code" feature.
import { Story, Meta } from '#storybook/angular/types-6-0';
import { ListItemsComponent } from './list-items.component';
import { Component } from '#angular/core';
export default {
title: 'Demo/ListItems',
component: ListItemsComponent,
} as Meta;
const Template: Story<ListItemsComponent> = (args: ListItemsComponent) => ({
props:args,
});
export const BasicDemo = Template.bind({})
BasicDemo.args={
items: ["Basic Demo", "Without interaction"]
}
// Create a dedicated component for the interactive story
#Component({
selector: 'story-list-items',
template: `
<core-list-items [items]="items"></core-list-items>
<input type="text" [(ngModel)]="value" /><button (click)="addItem()">add</button>
`,
})
class InteractiveDemoComponent{
items = [];
value: string = '';
addItem(){
this.items = [...this.items, this.value];
this.value = ""
}
}
const InteractiveTemplate: Story<ListItemsComponent> = (args: ListItemsComponent) => ({
props:args,
component: InteractiveDemoComponent,
});
export const InteractiveDemo = InteractiveTemplate.bind({});
InteractiveDemo.args = {
items: ["Interactive Demo"]
}

React Redux Input handle

I'm trying to handle simple input value using react-redux and then trying to display it. I know how to display it but i have no idea how to submit input value from component to redux store. I searched web and found nothing. Can someone explain how to do this? I'm totally new to react-redux
import React from "react";
import "./App.css";
import { connect } from "react-redux";
import { useState } from "react";
import { updateValue, addValue } from "./actions/inputActions";
function App(props) {
const [value, setValue] = useState("");
const handleChange = (e) => {
setValue(e.target.value);
};
return (
<div className="App">
<form onSubmit={(value) => props.submitValue(value)}>
<input onChange={handleChange} value={value} type="text" />
<button type="submit">Add</button>
</form>
<h1>{props.value}</h1>
</div>
);
}
const mapStateToProps = (state) => {
return {
value: state.value,
};
};
const mapDispatchToProps = (dispatch) => {
return {
submitValue: (e, value) => {
e.preventDefault();
dispatch(addValue(value));
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
Update your onSubmit function with the value stored in your local state, like this:
<form onSubmit={(e) => {
e.preventDefault();
props.submitValue(value)
}}>
<input onChange={handleChange} value={value} type="text" />
<button type="submit">Add</button>
</form>
And your mapDispatchToProps function like this:
const mapDispatchToProps = (dispatch) => {
return {
submitValue: (value) => {
dispatch(addValue(value));
},
};
};

redux-form/immutable, how to update state in reducer.plugin?

currently I'm trying to use redux-form/immutable in ma brand new project and I'm facing so problems which I can't resolve (aspecially, with this cool reducer.plugin), probably couse I'm kinda new to immutable and stuff like that.
Appreciating and advice or help on topic.
so, first of all:
import { combineReducers } from 'redux-immutable';
import routing from './routeReducer';
import { reducer as formReducer } from 'redux-form/immutable';
const rootReducer = combineReducers({
routing,
form: formReducer.plugin({
signupForm: (state, action) => {
switch(action.type) {
case 'SIGNUP_FACEBOOK':
return {
console.log(state);
}
default:
return state
}
}
})
});
while non of the forms field and touched this console.log(state) returns undefined, so here is the question: how may I initialize the form with some kind of state and actually update in on some sort of action ('SIGNUP_FACEBOOK' for this example)?
here is the form code sample:
import React, { PropTypes } from 'react';
import { Field, reduxForm } from 'redux-form/immutable';
import renderInputControl from '../../../common/InputControl';
import validate from './validate';
const SignUpForm = (props) => {
const { handleSubmit, submitting, invalid } = props;
return (
<form onSubmit={handleSubmit} className='signup__form'>
<Field name='name' type='text' component={renderInputControl} label='Full Name'/>
<Field name='email' type='email' component={renderInputControl} label='Email'/>
<Field name='password' type='password' component={renderInputControl} label='Password'/>
<Field name='tel' type='tel' component={renderInputControl} label='Phone Number'/>
<button type='submit' disabled={submitting || invalid}>Sign Up</button>
</form>
);
};
SignUpForm.propTypes = {
handleSubmit: PropTypes.func.isRequired,
onSubmit: PropTypes.func,
submitting: PropTypes.bool,
invalid: PropTypes.bool
};
export default reduxForm({
form: 'signupForm',
validate
})(SignUpForm);
and the second question is: even after I touch any of the fields (so it actually get some state, e.g. console.log(state) returns Map...), how should I update it, couse code:
state.getIn(['fields', 'name']).set('visited', false).set('touched', false)
which should set 'touched' and 'visited' to false doesn't do anything?
Best of luck!

Props are undefined in redux component

Given the following component, which is structually similar to redux's demo component.
My primary issue is that props is always undefined even if the state in the store is perfectly valid
Note: In the link I'm looking at the 'containers/AddTodo.js', if the link doesn't directly take you to the snippet
import React from 'react';
import { connect } from 'react-redux';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import Label from 'react-bootstrap/lib/Label';
let HeaderContainer = ({props}) => { //props = undefined
return(
<div>
<Label bsStyles="warning">
<Glyphicon glyph="exclamation" />
{props.openCount}
</Label>
<Label bsStyle="success">
<Glyphicon glyph="ok" />
{props.completedCount}
</Label>
</div>
);
}
const mapStateToProps = (state) => {
return {
openCount: state.tasks.filter( task => !task.completed).length,
completedCount: state.tasks.filter( task => task.completed ).length
};
}
HeaderContainer = connect(mapStateToProps)(HeaderContainer);
export default HeaderContainer;
Remove {} from the ({props}). If you want to use destructuring, try ({openCount, completedCount})
let HeaderContainer = (props) => //...
let HeaderContainer = ({openCount, completedCount}) => //..

Resources