updating state in reducer not updating component

I was trying to update my state from an api, using this approach. So I created the following code in my reducer:

export default function(state = null, action){
    switch(action.type){
        case ROUTING_BOOKS:
            return action.payload.data;
        case UPDATE_BOOK:
            let newVals = state.map((item)=>{
                if(item.MatItemKey === action.meta.book.MatItemKey){
                    return update(item, {$merge: action.payload.data})

                }else{
                    return item
                }
            });
            console.log(newVals);
            return newVals
    }
    return state
}

newVals returns back the values I want in my state. However, the component that is using this reducer using connect:

function mapStateToProps(state){
    return{
        routing: state.activeRouting,
        routingBooks: state.routingBooks
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(RoutingTable);

ROUTING_BOOKS updates the component, but my calls to UPDATE_BOOK appear to update the reducer, but not the RoutingTable component.

EDIT: Sample data from UPDATE_BOOK

[{“RoutingStepKey”:4752755,”MaterReqPer”:1,”MatItemKey”:216158,”MatReqPc”:1,”StepID”:”000010″,”OperationType”:”M”,”OperationDesc1″:”Default Material Step”,”LongDesc”:”Who Am I?”},{“RoutingStepKey”:4752756,”MaterReqPer”:1,”MatItemKey”:216056,”MatReqPc”:1,”StepID”:”000020″,”OperationType”:”M”,”OperationDesc1″:”Default Material Step”,”LongDesc”:”Mammals Love Their Babies”},{“RoutingStepKey”:4752758,”MaterReqPer”:1,”MatItemKey”:218213,”MatReqPc”:1,”StepID”:”000030″,”OperationType”:”M”,”OperationDesc1″:”Default Material Step”,”LongDesc”:”My Forest”}]

Sample data from Update_Book:

[{“RoutingStepKey”:4752755,”MaterReqPer”:1,”MatItemKey”:216158,”MatReqPc”:1,”StepID”:”000010″,”OperationType”:”M”,”OperationDesc1″:”Default Material Step”,”LongDesc”:”Who Am I?”…more data added},{“RoutingStepKey”:4752756,”MaterReqPer”:1,”MatItemKey”:216056,”MatReqPc”:1,”StepID”:”000020″,”OperationType”:”M”,”OperationDesc1″:”Default Material Step”,”LongDesc”:”Mammals Love Their Babies”…more data added},{“RoutingStepKey”:4752758,”MaterReqPer”:1,”MatItemKey”:218213,”MatReqPc”:1,”StepID”:”000030″,”OperationType”:”M”,”OperationDesc1″:”Default Material Step”,”LongDesc”:”My Forest”…more data added}]

Combine Reducers:

import {combineReducers} from 'redux';
import books from './books';
import routings from './routings';
import activeBook from './activeBook';
import activeRouting from './activeRouting';
import options from './options';
import login from './login';
import uiState from './uiState';
import routingBooks from './routingBooks';

const rootReducer = combineReducers({
    books,
    routingBooks,
    activeBook,
    activeRouting,
    options,
    routings,
    login,
    uiState
});

export default rootReducer;

Meteor setup (boilerplate) with server-render and react-router?

I’ve only been developing with Meteor 1.4 for a while, and now made the jump to 1.6. Things sure have changed (for the worse).

Meteor used to be so easy to get started with. Now everything is a jumbled mess. It seems like every package wants to insert itself right at the start, so that you can’t just import it and use it anymore, you have to change the setup/boilerplate of your app to get it to work. That also means the official documentation is useless because it can’t account for every package you want to use.

Anyway, I want to get started with react-router and server-render, which also requires react-helmet (I think). All of these are new to me and hey, they want to insert themselves right away and they all have awful documentation to begin with.

Here’s what I have so far, based on googling:

lib/main.js:

import React from 'react'

import { Helmet } from 'react-helmet'

import App from '../imports/ui/App.js'

if (Meteor.isClient) {
  import { hydrate } from 'react-dom'

  hydrate(<App />, document.getElementById('app'))
}

else {
  import { renderToString } from 'react-dom/server'
  import { onPageLoad } from 'meteor/server-render'
  import NodeCache from 'node-cache'

  const renderCache = new NodeCache({stdTTL: 432000})

  onPageLoad((sink) => {
    const path = sink.request.url.path
    let htmlString = renderCache.get(path)
    if (!htmlString) {
      htmlString = renderToString(<App location={path} />)
      const helmet = Helmet.renderStatic()

      renderCache.set(path, htmlString)
      renderCache.set(path + "_title", helmet.title.toString())
      renderCache.set(path + "_meta", helmet.meta.toString())
      renderCache.set(path + "_link", helmet.link.toString())
    }

    sink.appendToHead(renderCache.get(path + "_title"))
    sink.appendToHead(renderCache.get(path + "_meta"))
    sink.appendToHead(renderCache.get(path + "_link"))
    sink.renderIntoElementById("app", htmlString);
  })

}

And then App.js is just an empty component right now.

I don’t know where to put my routing, or how (the docs assume you already know, for some reason). I think it also needs to insert itself in the hydrate() method on the client, but the example I got it from did not do that so I don’t really know.

I don’t know whether to put my main.html on the client or both client and server.

I don’t know how to set titles and meta tags and whatnot for each route. (I thought this would actually be in the documentation for react-helmet since that’s all it’s supposed to do but no…)

Can anyone help me with the rest of this boilerplate? I have no idea what’s going on in the Meteor world anymore.

How to test a component using Enzyme which loads based on Process.env variable

I have a DIV which loads based on Process.env variable could any one point me in a direction on how to test this section ?

{ process.env.STYLE === 'RNR' &&
            <div className="price-option">
            <span>$ <input type="text" ref="minInput" placeholder="Min" defaultValue={minValue} /></span>
            <span>{i18n.l('to ')} $ <input type="text" ref="maxInput" defaultValue={maxValue} placeholder="Max" /></span>
            <button onClick = {this.filterPrice.bind(this)} ref={(node) => { this.minMaxfilter = node }} >{i18n.l('Go')}</button>
            </div>
        }

In Ant Design, how can we center vertically in ?

Please see my React code example:

import React from 'react';
import { Row, Col, Icon } from 'antd';
const MyRow = () => (
  <Row type="flex" align="middle">
    <Col md={10}>Trouble is a friend</Col>
    <Col md={10}><Icon type="play-circle-o" /></Col>
    <Col md={4}><div>Lenka</div></Col>
  </Row>
);

...

When I rendered <MyRow />, I found that the text in <Row> was centered vertically well, but the <Icon> component didn’t do so. So that my <MyRow> didn’t look good. I expected all the content, not only the text but also the SVG in <Row> could be centered vertically.

I also tried other icon library, e.g. react-icons-kit, which did not work.

Does anyone have an idea?

React: Calling parent’s method through inheritance

I understand that inheritance is not recommended by FB. The ideal way is composition.Since the structure of this app was set up previously by senior dev years ago, I don’t have the power to change it as a junior dev

I am trying to invoke a parent component’s method in child component. I have a parent component ParentComp, that looks like following:

export default class ParentComp extends GrandParentComp {
  constructor(props) {
    super(props);
  }

  foo() {
    console.log("Hello World")
  }

  componentDidMount() {
    this.foo();
  }
}

The parent component is bundled like a module with webpack, so i cant pass child component as property.

And the child component that looks like this:

import ParentComp from './ParentComp'

export default class ChildComp extends ParentComp {
  constructor(props){
    super(props)

    this.foo = this.foo.bind(this);
  }
}

Is this the right way to trigger parent component’s method through inheritance? Because “Hello World” was never print on the console.

What I have to tried: I tried to look up FB’s document, but they simply skipped explaining inheritance saying it is not recommended.

What I need help with: If I have to do it through inheritance, what is the right way to do that?

TypeError: evt.target is null in functional setState

What’s the major difference bewteen these two functions?

handleOnChange(evt) {
    this.setState(() => ({
        tickerName: evt.target.value
    }));
}

handleOnChange(evt) {
    this.setState({ tickerName: evt.target.value });
}

And why with the handleOnChange() function that change the state directly this works fine?

<input
    type="text"
    value={this.state.tickerName}
    onChange={(evt) => this.handleOnChange(evt)} 
/>

When I use the first function that change the state with a callback I get this error:

TypeError: evt.target is null

Routing with React Router v4 in embedded React Apps

I builded a little questionnaire with React and React-router v4.
I developed with create-react-app.
It is working fine when I build it as standalone page. The Router routes like I want.

But now I made a build for a page in Mahara (https://mahara.org/) and another one for WordPress.

In Mahara it is a plugin and the questionnaire comes in a part of the Mahara page.
In WordPress the questionnaire is a part of the whole WordPress Page.

In both variants the router doesn’t work. The path “/” is not found. So the default “not found” page appears.

I edited the homepage property in the package.json and the basename attribute for the BrowserRouter.

Is it generally possible to make the router functioning, when the React app is not a standalone page?

Maybe the problem is, that in both platforms(Mahara/Wordpress) the url is not really the one where the questionnaire exists?

In mahara for example the questionnaire exists in “http://mahara_17_10.local/blocktype/learningstyle/js/build/” but the url shows: “http://mahara_17_10.local/view/view.php?id=3842“. This public page is generated with Smarty templating and some php.

I tried both: The real place, where the React build folder exists, or the generated url (the second one). But I had no luck so far.

here some code:
package.json:

"homepage": "http://mahara_17_10.local/view/view.php?id=3842",

BrowserRouter:

<BrowserRouter basename="/view/view.php?id=3842">

Router in Main Component:

<div className={ApplicationClassNames}>
                    <ApplicationHeader
                        title={title}
                        count_blocks={count_blocks}
                        number_of_blocks_overall={number_of_blocks_overall}
                    />
                    <Switch>
                        <Route exact path='/' render={() => (
                        <ApplicationBody
                            page_now={page_now}
                            count_cats={count_cats}
                            count_pages={count_pages}
                            categories_pages_quantity={categories_pages_quantity}
                            catValuesCountAll={catValuesCountAll}
                            language={language}
                            show_result={false}
                            values_not_for_categories={values_not_for_categories}
                        />
                        )}/>
                        <Route path='/wtf' component={Result} />
                        <Route><div>Not found</div></Route>
                    </Switch>
                </div>

So my questions are:

1: Is it generally possible to make the router functioning, when the React app is not a standalone page?

  1. If yes, how for excample in wordpress or mahara. Maybe anybody knows a tutorial oder something else what can help me here.

I would be very happy, if somebody could help me here a little bit.
thanx =)

Selected option in onChange with react / redux

I’m playing with react and redux and I can’t do something that should be trivial in my opinion.

I have a component that is just a select with few options. I simply want to update my redux store when the user choose a different option with the selected value.
I think I’m pretty close but I can’t figure out how to pass the new value to my reducer.

Here is the code :

const StoresList = ({ onChangeSelect, value }) => (
  <div>
    <select defaultValue = {value}  onChange= {() => onChangeSelect(???)}>
      <option value="12">MyStore</option>
      <option value="15">YourStore</option>
      <option value="18">OurStore</option>
    </select>
  </div>
)

const mapStateToProps = state => {
  return {
    value: state.currentStore
  }
}

const mapDispatchToProps = dispatch => {
  return {
    onChangeSelect: idStore => {
      dispatch(changeStore(idStore))
    }
  }
}

//connect is a function that gathers the store, the behavior and the view
//It returns the component that we really want to use
const StoresListContainer = connect(mapStateToProps, mapDispatchToProps)(StoresList)
export default StoresListContainer

I put “???” in the code to show where I’m clueless.
As for now, the plugin chrome for redux sees my action but I don’t know how to pass the new value of the select.

Controlling several textFields from MaterialUI in React

I need help getting more than one textfield to update but the events are clashing. When I update one field it alters or removes the other. This is my code now

class ClientConn extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: '192.168.60.51',
            value2: '8080',
            value3: 'ContentManager',
            defaultToggled: true,
        };
    }

    handle1Change = (event) => {
        this.setState({
            value: event.target.value,
        });
    };

    handle2Change = (event) => {
        this.setState({
            value2: event.target.value2,
        });
    };

    handle3Change = (event) => {
        this.setState({
            value3: event.target.value3,
        });
    };

    render() {
        return (
            <div>
                <TextField
                    id="host-address"
                    value={this.state.value}
                    onChange={this.handle1Change}
                />
                <TextField
                    id="port"
                    value={this.state.value2}
                    onChange={this.handle2Change}
                />
                <TextField
                    id="folder"
                    value={this.state.value3}
                    onChange={this.handle3Change}
                />
            </div>      
            <div>
                 {this.state.defaultToggled ? "https://" : "http://"}{this.state.value}:{this.state.value2}/{this.state.value3}
            </div>
        </div>
     );
   }
}

They pre-populate fine. Like this

https://192.168.60.51:8080/ContentManager

I need to be able to update each field and it will update that link’s respective value on-the-fly before I send it to the server/database. So if I change the port from 8080 to 8088, it will update the link as I type. Same with the folder and even the host address.

Thanks in advance!

How to combine a styles object with an inline style in React Native?

I am trying to combine an inline style transform: [{ rotate: '180deg'}] with an already existing styles object styles.buttonText without modifying the styles object. I have tried the following ways:

<Text style={{...styles.buttonText, transform: [{ rotate: '180deg'}]}}>^</Text>

and

<Text style={{...styles.buttonText, ...{transform: [{ rotate: '180deg'}]}}}>^</Text>

and

<Text style={Object.assign({}, styles.buttonText, {transform: [{ rotate: '180deg'}]})}>^</Text>

But I keep getting this same error message:

TypeError: In this environment the sources for assign MUST be an
object. This error is a performance optimization and not spec
compliant.

Does anyone know what is going on or how I can get this to work?