Props not being updated when Redux action is called - javascript

Just a disclaimer - my code worked when I had problematic function in my main component. After I exported it it stopped behaving as it should. My theory is because somehow props are not being updated properly.
Anyway, I have a component, which after it's clicked it starts listening on window object and sets proper store element to "true" and depending on next object clicked acts accordingly. After incorrect object is clicked, the store should revert to false, and it does, however the props are still "true" as shown on the screenshot below.
How can I solve this? Perhaps there is a way that function could take store as parameter instead of props? Or im calling actions inproperly or im missing something completely?
Code below:
Main component (relevant parts?):
import React from 'react';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import {activate} from '../../actions/inventory'
import { setModalContent, setModalState } from '../../actions/modal';
import inventoryReducer from '../../reducers/inventory';
import {chainMechanics} from './itemMechanics/chainMechanics';
class ItemRenderer extends React.Component{
handleBoltcuttersClicked(){
this.props.activate('boltcutters', true);
setTimeout(() => chainMechanics(this.props), 100)
}
inventoryItemRender(){
let inventoryItem = null;
if(this.props.inventory.items.boltcutters){
inventoryItem = <a className={this.props.inventory.activeItem.boltcutters ? "ghost-button items active " : "ghost-button items"} href="#" id='boltcuttersId' onClick={() => this.handleBoltcuttersClicked()}>Boltcutters</a>
}
return inventoryItem;
}
render(){
let renderItems = this.inventoryItemRender();
return(
<div>
{renderItems}
</div>
)
}
}
const mapStateToProps = (state) => {
return {
level: state.level,
inventory: state.inventory
}
}
function mapDispatchToProps(dispatch) {
//dispatch w propsach
return(
bindActionCreators({activate: activate, setModalState: setModalState, setModalContent: setModalContent }, dispatch)
)
}
export default connect(mapStateToProps, mapDispatchToProps)(ItemRenderer);
File with problematic function:
import {activate} from '../../../actions/inventory'
import { setModalContent, setModalState } from '../../../actions/modal';
export function chainMechanics(props){
let clickedElement;
window.onclick = ((e)=>{
console.log(clickedElement, 'clickedelement', props.inventory.activeItem.boltcutters)
if(props.inventory.activeItem.boltcutters===true){
clickedElement = e.target;
if(clickedElement.id === 'chainChainedDoor'){
props.activate('boltcutters', false);
props.setModalContent('Chain_Broken');
props.setModalState(true);
} else if(clickedElement.id === 'boltcuttersId'){
console.log('foo')
} else {
props.activate('boltcutters', false);
props.setModalContent('Cant_Use');
props.setModalState(true);
console.log("props.inventory.activeItem.boltcutters", props.inventory.activeItem.boltcutters);
}
}
})
}
My actions:
const inventoryReducer = (state = inventoryDefaultState, action) => {
switch (action.type) {
case 'ACTIVE':
console.log(action)
return {
...state,
activeItem: {
...state.activeItem,
[action.item]: action.isActive
}
}
default:
return state;
}
}
How I configure store:
export default () => {
const store = createStore(
combineReducers({
level: levelReducer,
modal: modalReducer,
inventory: inventoryReducer,
styles: stylesReducer
}),
applyMiddleware(thunk)
)
return store;
}
I believe thats eveyrthing needed? If not please do let me know, I've been trying to make this work for a long time.
Screenshot:

You can use the React's function componentWillReceiveProps. That would trigger a rerender like this (and also make use of next props/state):
componentWillReceiveProps(next) {
console.log(next);
this.inventoryItemRender(next);
}
inventoryItemRender(next){
const inventory = next.inventory ? next.inventory : this.props.inventory;
let inventoryItem = null;
if(inventory.items.boltcutters){
inventoryItem = <a className={inventory.activeItem.boltcutters ? "ghost-button items active " : "ghost-button items"} href="#" id='boltcuttersId' onClick={(next) => this.handleBoltcuttersClicked(next)}>Boltcutters</a>
}
return inventoryItem;
}
handleBoltcuttersClicked(props){
this.props.activate('boltcutters', true);
setTimeout(() => chainMechanics(props), 100)
}

Related

React Component not updating even after duplication of state in Redux reducer

Context
The goal is to have a component with a key name being react-rendered in App.js when I press a specific key, registered in another component. The information is being passed thorugh a redux managed state.
The problem
It's simple :
I'm updating my state in my redux reducer but even when duplicating it (I can see it thanks to the redux dev tool that allows me to watch my prevState and my nextState being different)
And the question is as simple :
Why my App.js component won't re-render even after connecting to and
duplicating my state ?
I think I made sure that my state was duplicated with the spreading operation and my redux dev tool display me a good state update without having my prevState and nextState duplicated. I looked through a lot of posts and found only people that forgot to duplicate their state in their reducers, which I did not.
So what's the problem here ??
DevTool Sample
Code
Here is the code, quite simple. The interesting piece is playSound and playedKeys:
App.js :
import React from 'react'
import './App.css';
import { connect } from 'react-redux';
import KeyComponent from './Components/Key'
import SoundPlayer from './Components/Sounds'
const mapStateToProps = (state) => ({
...state.soundReducer
})
class App extends React.Component {
constructor(props) {
super(props);
}
render(){
return (
<div>
{console.log(this.props)}
{
this.props.playedKeys.map(key =>{
<KeyComponent keyCode={key}> </KeyComponent>
})
}
<SoundPlayer></SoundPlayer>
</div>
);
}
}
export default connect(mapStateToProps)(App);
Reducer
export default (state = {allSounds:{},playedKeys:[]}, action) => {
switch (action.type) {
case 'ADD_SOUND':
return reduce_addSound({...state},action)
case 'PLAY_SOUND':
return reduce_playSound({...state,playedKeys : [...state.playedKeys]},action)
default:
return state
}
}
function reduce_addSound (state,action){
let i = 0
state.allSounds[action.payload.key] = { players : new Array(5).fill('').map(()=>(new Audio())) , reader : new FileReader()}
//load audioFile in audio player
state.allSounds[action.payload.key].reader.onload = function(e) {
state.allSounds[action.payload.key].players.forEach(player =>{
player.setAttribute('src', e.target.result);
player.load();
player.id = 'test'+e.target.result+ i++
})
}
state.allSounds[action.payload.key].reader.readAsDataURL(action.payload.input.files[0]);
return state
}
function reduce_playSound(state,action){
state.playedKey = action.payload.key;
if(!state.playedKeys.includes(state.playedKey))
state.playedKeys.push(action.payload.key);
return state
}
Action
export const addSound = (key, input,player) => (dispatch,getState) => {
dispatch({
type: 'ADD_SOUND',
payload: {key : key, input : input}
})
}
export const playSound = (key) => (dispatch,getState) => {
dispatch({
type: 'PLAY_SOUND',
payload: {key : key}
})
}
The component registering the keypresses
import React from 'react'
import { connect } from 'react-redux';
import { playSound } from '../../Actions/soundActions';
const mapStateToProps = (state) => ({
...state.soundReducer
})
const mapDispatchToProps = dispatch => ({
playSound: (keyCode) => dispatch(playSound(keyCode))
})
class SoundPlayer extends React.Component {
constructor(props) {
super(props);
}
componentDidMount () {
this.playSoundComponent = this.playSoundComponent.bind(this)
document.body.addEventListener('keypress', this.playSoundComponent);
}
keyCodePlayingIndex = {};
playSoundComponent(key){
if(this.props.allSounds.hasOwnProperty(key.code)){
if(!this.keyCodePlayingIndex.hasOwnProperty(key.code))
this.keyCodePlayingIndex[key.code] = 0
this.props.allSounds[key.code].players[this.keyCodePlayingIndex[key.code]].play()
this.keyCodePlayingIndex[key.code] = this.keyCodePlayingIndex[key.code] + 1 >= this.props.allSounds[key.code].players.length ? 0 : this.keyCodePlayingIndex[key.code] + 1
console.log(this.keyCodePlayingIndex[key.code])
}
this.props.playSound(key.code);
}
render(){
return <div>
<h1 >Played : {this.props.playedKey}</h1>
{Object.keys(this.keyCodePlayingIndex).map(key =>{
return <p>{key} : {this.keyCodePlayingIndex[key]}</p>
})}
</div>
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SoundPlayer);
Issue
You are mutating your state object.
state.allSounds[action.payload.key] = ...
state.playedKey = action.payload.key;
Solution
Update your reducer functions to return new state objects, remembering to correctly shallow copy each level of depth that is being updated.
export default (state = { allSounds: {}, playedKeys: [] }, action) => {
switch (action.type) {
case 'ADD_SOUND':
return reduce_addSound({ ...state },action);
case 'PLAY_SOUND':
return reduce_playSound({ ...state, playedKeys: [...state.playedKeys] }, action);
default:
return state
}
}
function reduce_addSound (state, action) {
const newState = {
...state, // shallow copy existing state
allSounds: {
...state.allSounds, // shallow copy existing allSounds
[action.payload.key]: {
players: new Array(5).fill('').map(()=>(new Audio())),
reader: new FileReader(),
},
}
};
// load audioFile in audio player
newState.allSounds[action.payload.key].reader.onload = function(e) {
newState.allSounds[action.payload.key].players.forEach((player, i) => {
player.setAttribute('src', e.target.result);
player.load();
player.id = 'test' + e.target.result + i // <-- use index from forEach loop
})
}
newState.allSounds[action.payload.key]
.reader
.readAsDataURL(action.payload.input.files[0]);
return newState;
}
function reduce_playSound (state, action) {
const newState = {
...state,
playedKey: action.payload.key,
};
if(!newState.playedKeys.includes(newState.playedKey))
newState.playedKeys = [...newState.playedKeys, action.payload.key];
return newState
}
Okay I've got it, it's always the simplest stupidest thing that we don't check huh.
Clarification
So my state was properly duplicated with reduce_addSound({ ...state },action) and reduce_playSound({ ...state, playedKeys: [...state.playedKeys] and like I wrote in my question, that wasn't the issue !
Issue
As old as it can get, I wasn't returning a component in my render function.. :
in App.js :
render(){
return (
<div>
{
this.props.soundReducer.playedKeys.map(key =>{
<KeyComponent keyCode={key}> </KeyComponent> //<-- NO return or parenthesis !!
})
}
<SoundPlayer></SoundPlayer>
</div>
);
}
Answer
App.js render function with parenthesis:
render(){
return (
<div>
{
this.props.soundReducer.playedKeys.map(key =>(
<KeyComponent key = {key} keyCode={key}> </KeyComponent> //<-- Here a component is returned..
))
}
<SoundPlayer></SoundPlayer>
</div>
);
}

MobX State Tree async actions and re-rendering React component

I am new to MST and is having a hard time finding more examples with async actions. I have an api that will return different data depending on the params you pass to it. In this case, the api can either return an array of photos or tutorials. I have set up my initial values for the store like so:
data: {
photos: [],
tutorials: []
}
Currently, I am using applySnapshot to update the store and eventually, that will trigger a re-render of my React component. In order to display both photos and tutorials, I need to call the api twice (Once with the params for photos and the second time for tutorials). I am running into an issue where the snapshot from the first update shows that photos and tutorials have the same values and only on the second update, do I get the correct values. I am probably misusing applySnapshot to re-render my React components. I would like to know the better/proper way of doing this. What is the best way to re-render my React components after the api has yielded a repsonse. Any suggestions are much appreciated
I have set up my store like this:
import { RootModel } from '.';
import { onSnapshot, getSnapshot, applySnapshot } from 'mobx-state-tree';
export const setupRootStore = () => {
const rootTree = RootModel.create({
data: {
photos: [],
tutorials: []
}
});
// on snapshot listener
onSnapshot(rootTree, snapshot => console.log('snapshot: ', snapshot));
return { rootTree };
};
I have created the following model with an async action using generators:
import {types,Instance,applySnapshot,flow,onSnapshot} from 'mobx-state-tree';
const TestModel = types
.model('Test', {
photos: types.array(Results),
tutorials: types.array(Results)
})
.actions(self => ({
fetchData: flow(function* fetchData(param) {
const results = yield api.fetch(param);
applySnapshot(self, {
...self,
photos: [... results, ...self.photos],
tutorials: [... results, ...self.tutorials]
});
})
}))
.views(self => ({
getPhoto() {
return self.photos;
},
getTutorials() {
return self.tutorials;
}
}));
const RootModel = types.model('Root', {
data: TestModel
});
export { RootModel };
export type Root = Instance<typeof RootModel>;
export type Test = Instance<typeof TestModel>;
React component for Photos.tsx
import React, { Component } from 'react';
import Spinner from 'components/Spinner';
import { Root } from '../../stores';
import { observer, inject } from 'mobx-react';
interface Props {
rootTree?: Root
}
#inject('rootTree')
#observer
class Photos extends Component<Props> {
componentDidMount() {
const { rootTree } = this.props;
if (!rootTree) return null;
rootTree.data.fetchData('photo');
}
componentDidUpdate(prevProps) {
if (prevProps.ctx !== this.props.ctx) {
const { rootTree } = this.props;
if (!rootTree) return null;
rootTree.data.fetchData('photo');
}
}
displayPhoto() {
const { rootTree } = this.props;
if (!rootTree) return null;
// calling method in MST view
const photoResults = rootTree.data.getPhoto();
if (photoResults.$treenode.snapshot[0]) {
return (
<div>
<div className='photo-title'>{'Photo'}</div>
{photoResults.$treenode.snapshot.map(Item => (
<a href={photoItem.attributes.openUrl} target='_blank'>
<img src={photoItem.url} />
</a>
))}
</div>
);
} else {
return <Spinner />;
}
}
render() {
return <div className='photo-module'>{this.displayPhoto()}</div>;
}
}
export default Photos;
Similarly, Tutorials.tsx is like so:
import React, { Component } from 'react';
import Spinner from '';
import { Root } from '../../stores';
import { observer, inject } from 'mobx-react';
interface Props {
rootTree?: Root;
}
#inject('rootTree')
#observer
class Tutorials extends Component<Props> {
componentDidMount() {
if (this.props.ctx) {
const { rootTree } = this.props;
if (!rootTree) return null;
rootTree.data.fetchData('tuts');
}
}
componentDidUpdate(prevProps) {
if (prevProps.ctx !== this.props.ctx) {
const { rootTree } = this.props;
if (!rootTree) return null;
rootTree.search.fetchData('tuts');
}
}
displayTutorials() {
const { rootTree } = this.props;
if (!rootTree) return null;
// calling method in MST view
const tutResults = rootTree.data.getTutorials();
if (tutResults.$treenode.snapshot[0]) {
return (
<div>
<div className='tutorials-title'>{'Tutorials'}</div>
{tutResults.$treenode.snapshot.map(tutorialItem => (
<a href={tutorialItem.attributes.openUrl} target='_blank'>
<img src={tutorialItem.url} />
</a>
))}
</div>
);
} else {
return <Spinner />;
}
}
render() {
return <div className='tutorials-module'>{this.displayTutorials()}</div>;
}
}
export default Tutorials;
Why are you using applySnapshot at all in this case? I don't think it's necessary. Just assign your data as needed in your action:
.actions(self => ({
//If you're fetching both at the same time
fetchData: flow(function* fetchData(param) {
const results = yield api.fetch(param);
//you need cast() if using Typescript otherwise I think it's optional
self.photos = cast([...results.photos, ...self.photos])
//do you really intend to prepend the results to the existing array or do you want to overwrite it with the sever response?
self.tutorials = cast(results.tutorials)
})
}))
Or if you need to make two separate requests to fetch your data it's probably best to make it two different actions
.actions(self => ({
fetchPhotos: flow(function* fetchPhotos(param) {
const results = yield api.fetch(param)
self.photos = cast([... results, ...self.photos])
}),
fetchTutorials: flow(function* fetchTutorials(param) {
const results = yield api.fetch(param)
self.tutorials = cast([... results, ...self.tutorials])
}),
}))
Regardless, it doesn't seem like you need applySnapshot. Just assign your data in your actions as necessary. There's nothing special about assigning data in an async action.

Increase Like count if post id is equal to action.payload

I am working on a social network app and I want to toggle the like count on clicking(it should increment by 1 on first click and should go back to null to when pressed again) for a particular post. But now when i click on the like button, nothing happens and the screen gets vanish. I am unable to get what is wrong with my code.
Here are my files-> action creator
export const fetchPosts = () => async dispatch => {
const request = await axios.get(`${ROOT_URL}/post`, {
headers: { Authorization: `${token}` }
});
dispatch({
type: FETCH_POSTS,
payload: request
});
};
export const incrementLikesCount = id => {
return {
type: INCREMENT_LIKES_COUNT,
payload: id
};
};
index.js(reducer)
import auth from "./authReducer";
import user from "./userReducer";
import post from "./postReducer";
export default combineReducers({
auth,
user,
post,
form: formReducer
});
postreducer.js
import _ from "lodash";
import { FETCH_POSTS, INCREMENT_LIKES_COUNT } from "../actions/types";
const initialState = {
postDetail: "",
likesCount: null
};
const post = (state = initialState, action) => {
switch (action.type) {
case FETCH_POSTS:
return {
...state,
postDetail: _.mapKeys(action.payload.data.data, "_id")
};
case INCREMENT_LIKES_COUNT:
return _.values(state.postDetail)
.reverse()
.map(post => {
if (action.payload === post._id) {
if (state.likesCount === null) {
console.log("I got executed");
return { ...state, likesCount: state.likesCount + 1 };
} else {
return {
...state,
likesCount: null
};
}
} else {
return {
state
};
}
});
default:
return state;
}
};
export default post;
and my react Component
import _ from "lodash";
// import uuid from "uuid";
import { connect } from "react-redux";
import React, { Component } from "react";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import {
faHeart,
faCommentAlt,
faShareAlt
} from "#fortawesome/free-solid-svg-icons";
import { fetchPosts, incrementLikesCount } from "../../../actions/FeedPost";
import "./FeedPosts.css";
class FeedPosts extends Component {
componentDidMount() {
if (!this.props.fetchPosts) {
return <div>Loading...</div>;
}
this.props.fetchPosts();
}
renderPosts = () => {
return _.values(this.props.post)
.reverse()
.map(post => (
<div key={post._id} className="post-content">
<img
src={require("../../../img/blue.jpeg")}
alt="user"
className="user-image"
/>
<span>{post.postBy}</span>
<span>{post.userDesignation}</span>
<li>{post.postText}</li>
<div className="fontawesome-icons">
<div className="like-font">
<FontAwesomeIcon
icon={faHeart}
onClick={() => this.props.incrementLikesCount(post._id)}
/>
<span>{this.props.likesCount}</span>
</div>
<div className="comment-font">
<FontAwesomeIcon icon={faCommentAlt} />
</div>
<div className="share-font">
<FontAwesomeIcon icon={faShareAlt} />
</div>
</div>
</div>
));
};
render() {
return (
<div>
<ul className="posts">{this.renderPosts()}</ul>
</div>
);
}
}
const mapStateToProps = state => ({
post: state.post.postDetail,
likesCount: state.post.likesCount
});
export default connect(
mapStateToProps,
{ fetchPosts, incrementLikesCount }
)(FeedPosts);
So, Basically my question is how can I increase the like count just for a particular post, because I was able to toggle the like button but it was increasing the like count of all the posts.
The following should kind of work but it would be easier to have state.posts as array instead of converting from array to object and object to array every time.
To be sure it'll work you need to show the code where you set state.posts
case INCREMENT_LIKES_COUNT:
return {
...state,
likesCount:state.likesCount+1,
//not sure why posts need to be an object instead of it being an array
posts:Object.entries(state.posts).reduce(
(result,[key,value])=>{
if(value._id===action.payload){
//you probably didn't set the initial likes but the reducer
// where you set state.posts isn't in your question
result[key]= {...value,likes:value.likes+1};
}else{
result[key]=value;
}
return result;
},
{}
)
}
Although after seeing this again I realize the posts is an object where the id is the key so you can make it simpler:
case INCREMENT_LIKES_COUNT:
return {
...state,
likesCount:state.likesCount+1,
//not sure why posts need to be an object instead of it being an array
posts:{
...state.posts,
[action.payload]:{
...state.posts[action.payload],
likes:state.posts[action.payload].likes+1
}
}
}

React/Redux component not updating

I am new to using Redux and cannot figure out why my Sidebar component is not being updated to open the drawer. I can see that my action is getting called but it doesn't seem to trigger any update in my component. I have tried to follow the Redux documentation and I can't see what I am missing as I have set my code up the same way.
I didn't want to fill the post up with code but let me know if you need any more information to help solve this. I'd appreciate any help, thanks.
Solution: I was using the wrong property on the state object so my component wasn't being updated. It should have been state.Sidebar.open not state.open.
const mapStateToProps = (state:any) => ({
open: state.Sidebar.open
});
Menu container:
import { connect } from 'react-redux';
import { toggleSidebar } from '../actions';
import Menu from '../components/Menu/Menu';
const mapStateToProps = (state:any) => ({
open: state.open ? state.open : false
});
const mapDispatchToProps = (dispatch:any) => ({
toggleSidebar: (open:boolean) => dispatch(toggleSidebar(open))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Menu);
Menu component:
class Menu extends React.Component<IMenuProps> {
private handleDrawerOpen = () => {
this.props.toggleSidebar(true);
}
private handleDrawerClose = () => {
this.props.toggleSidebar(false);
}
public render() {
return (
<div>
<MenuBar
handleDrawerOpen={this.handleDrawerOpen}
/>
<SideBar
open={this.props.open}
handleDrawerClose={this.handleDrawerClose}
/>
</div>
);
}
}
Sidebar:
class Sidebar extends React.Component<ISideBarProps> {
public render() {
return (
<div>
<Drawer
open={this.props.open}
onClose={this.props.handleDrawerClose}>
<div
tabIndex={0}
role="button"
>
<AdministrationItems />
</div>
</Drawer>
</div>
);
}
}
*Edit
Reducer:
const sidebar = (state = { open: false }, action:any) => {
switch (action.type) {
case TOGGLE_SIDEBAR: {
return {
open: action.open
};
}
default: {
return state;
}
}
};
Action:
export const toggleSidebar = (open:boolean) => ({
open,
type: TOGGLE_SIDEBAR,
});
I believe the error is in the reducer. Try replacing the reducer with:
const sidebar = (state = { open: false }, action:any) => {
switch (action.type) {
case TOGGLE_SIDEBAR: {
return {
...state,
open: action.open
};
}
default: {
return state;
}
}
};
You should always spread the state for every case. Let me know if it worked
Solution: I was using the wrong property on the state object so my component wasn't being updated. It should have been state.Sidebar.open not state.open.
const mapStateToProps = (state:any) => ({
open: state.Sidebar.open
});

React losing focus on input field (component added dynamically)

Stack : React16, ES6, Redux
I'm currently unable to figure what's wrong here. The goal here is to add dynamically an infinite number of components (one by one) when clicking on an add button.
I need to make them appear, if possible by pair or more, e.g. if I click on the ADD button, there should be 2 fields appearing each time (one select field and one textfield at the same time, for ex)
I'm able to make the components appear, with the help of Redux, and I'm also able to manage the datas correctly (everything's wired on the back of the app)
THE PROBLEM HERE :
When trying to type text in an input field, it's ALWAYS losing the focus. I've seen that each time I update my props, the whole component named MultipleInputChoiceList is mounted again, and that each fields are re-created anew. That's what I need to fix here :
EDIT : The MultipleInputChoiceList component is mounted via a Conditional Rendering HOC (It takes some values and check if they are true, if they are, it's rendering the component without touching the whole form)
ConditionalRenderingHOC.js
import React from 'react'
import {connect} from 'react-redux'
import _ from 'lodash'
const mapStateToProps = state => {
return {
form: state.form.form
}
}
const mapDispatchToProps = dispatch => {
return {
}
}
/**
* HOC Component to check conditional rendering on form component, using requireField property
* To be enhanced at will
*/
export default (WrappedComponent, formItem = {}) => {
class ConditionalRenderingHOC extends React.Component {
componentWillMount() {
//Check if all informations are available
if (formItem.requireField !== undefined) {
const requireField = formItem.requireField
if (requireField.value !== undefined &&
requireField.name !== undefined &&
requireField.field !== undefined &&
requireField.property !== undefined) {
//If everything's here let's call canBeRendered
this.canBeRendered()
}
}
}
//Check if the count of fetched values is directly linked to the number of fetched config asked, if true, return the same number
canBeRendered() {
formItem.requireField.isRendered = false
let required = formItem.requireField
let isEqual = false
if (this.props.form[required.field] !== undefined) {
let field = this.props.form[required.field]
_.forEach(field.value, (properties, index) => {
if (properties[required.name] !== undefined) {
if (properties[required.name] === required.value) {
if (properties[required.property] === required.isEqualTo) {
formItem.requireField.isRendered = true
isEqual = true
}
}
}
})
}
return isEqual
}
render() {
let isConditionMet = this.canBeRendered()
let render = null
if (isConditionMet === true) {
render = <WrappedComponent items={formItem}/>
}
return (<React.Fragment>
{render}
</React.Fragment>)
}
}
return connect(mapStateToProps, mapDispatchToProps)(ConditionalRenderingHOC)
}
The code
//Essentials
import React, { Component } from 'react'
import _ from 'lodash'
//Material UI
import TextField from 'material-ui/TextField'
import IconButton from 'material-ui/IconButton'
import AddBox from 'material-ui/svg-icons/content/add-box'
//Components
import SelectItemChoiceList from '../form/SelectItemChoiceList'
import TextFieldGeneric from './TextFieldGeneric'
//Redux
import { connect } from 'react-redux'
import { createNewField } from '../../../actions/formActions'
const mapStateToProps = (state) => {
return {
form: state.form.form
}
}
const mapDispatchToProps = (dispatch) => {
return {
createNewField: (field, state) => dispatch(createNewField(field, state))
}
}
class MultipleInputChoiceList extends Component {
constructor(props) {
super(props)
this.state = {
inputList: [],
}
}
onAddBtnClick() {
const name = this.props.items.name
/**Create a new field in Redux store, giving it some datas to display */
this.props.createNewField(this.props.form[name], this.props.form)
}
render() {
const name = this.props.items.name
/**I think the error is around this place, as it always re-render the same thing again and again */
const inputs = this.props.form[name].inputList.map((input, index) => {
switch(input) {
case 'selectfield': {
return React.createElement(SelectItemChoiceList, {
items: this.props.form[name].multipleField[index],
key:this.props.form[name].multipleField[index].name
})
}
case 'textfield': {
return React.createElement(TextFieldGeneric, {
items: this.props.form[name].multipleField[index],
index:index,
key:this.props.form[name].multipleField[index].name
})
}
default: {
break
}
}
})
return (
<div>
<IconButton onClick={this.onAddBtnClick.bind(this)}>
<AddBox />
</IconButton>
{inputs}
</div>
)
}
}
const MultipleInputChoiceListRedux = connect(mapStateToProps, mapDispatchToProps)(MultipleInputChoiceList)
export default MultipleInputChoiceListRedux
And the TextField used here :
TextFieldGeneric.js
//Essentials
import React, { Component } from 'react';
//Components
import TextField from 'material-ui/TextField'
//Redux
import { connect } from 'react-redux'
import { validateField, isValid } from '../../../actions/formActions'
const mapStateToProps = (state) => {
return {
form: state.form.form
}
}
const mapDispatchToProps = (dispatch) => {
return {
validateField: (field) => dispatch(validateField(field)),
isValid: () => dispatch(isValid())
}
}
class TextFieldGeneric extends Component {
constructor(props) {
super(props)
this.state = {
form: {},
field: {},
index: 0
}
}
componentWillMount() {
console.log(this.props)
//first, let's load those dynamic datas before rendering
let form = this.props.form
let index = this.props.index
/** Check if there's a correctly defined parent in form (taken from the name) */
let matchName = /[a-zA-Z]+/g
let origin = this.props.items.name.match(matchName)
//form.company.value = this.getCompaniesFormChoice()
this.setState({form: form, field: form[origin], index: index})
}
//setState and check validationFields if errors
handleFieldChange(event){
const name = event.target.name
const value = event.target.value
//Change value of state form field
const item = this.props.items
item.value = value
//validate each fields
this.props.validateField(item)
//validate form
this.props.isValid()
event.preventDefault()
}
render() {
const index = this.state.index
console.log(index)
return (
<React.Fragment>
<TextField
key={index}
floatingLabelText={this.state.field.multipleField[index].namefield}
name={this.state.field.multipleField[index].namefield}
floatingLabelFixed={true}
value = {this.state.field.multipleField[index].value}
onChange = {this.handleFieldChange.bind(this)}
errorText={this.state.field.multipleField[index].error === 0 ? '' : this.state.field.multipleField[index].error}
/>
</React.Fragment>
)
}
}
const TextFieldGenericRedux = connect(mapStateToProps, mapDispatchToProps)(TextFieldGeneric)
export default TextFieldGenericRedux
I also do understand that a part of the problem lies in the render method of the parent class (MultipleInputChoiceList.js) ...
Any help or comments REALLY appreciated!
As of now, I've not come to a real answer to that question, as it's a structural problem in my data (When updating a field via a Redux action, it's re-rendering the whole component). Maybe stock those data elsewhere would be a better option.
I've only used a onBlur method on the field, that dismiss the validation I want to do on each user input, but for the moment I could not think to another viable solution.
So far, the TextFieldGeneric.js looks like that :
//setState and check validationFields if errors
handleFieldChange(event){
this.setState({value: event.target.value})
event.preventDefault()
}
handleValidation(event){
const value = this.state.value
//Change value of state form field
const item = this.props.items
item.value = value
//validate each fields
this.props.validateField(item)
//validate form
this.props.isValid()
}
render() {
return (
<React.Fragment>
<TextField
name='name'
floatingLabelFixed={true}
value = {this.state.value}
onChange = {this.handleFieldChange.bind(this)}
onBlur = {this.handleValidation.bind(this)}
/>
</React.Fragment>
)
}
If anyone have another solution, I'll gladly hear it !

Categories

Resources