Incorrect integration into React props - reactjs

I am trying to implement my first React-Redux app and got TypeError: Cannot read property 'map' of undefined from bundle.js. I guess it is associated with jokes array and its incorrect integration into my React jokeList component props:
import React from 'react';
import {connect} from 'react-redux';
class ListOfJokes extends React.Component {
constructor(props) {
super(props)
}
render() {
const {jokes} = this.props;
return (
<ul>
{jokes.map(joke => (<li>joke</li>))}
</ul>
)
}
}
const mapStateToProps = state => ({
jokes: state.jokes
})
export default connect(mapStateToProps, null)(ListOfJokes);
What is actually wrong with it?

Are you sure that store.jokes always contains something? If you fetch the data asynchronously, then on the first render store.jokes may be undefined. If that's the case then do:
const mapStateToProps = state => ({
jokes: state.jokes || []
})

Use a conditional loop to check jokes has or not. when sets the joke then it will mapping.
{jokes.length !== 0 ?
jokes.map(joke => (<li>joke</li>)) : (<li>no jokes</li>)
}

Related

The data that comes from an API end point is undefined in the child component in React

Good day to all!
I have this situation: I use Apollo client to get data from a GraphQL API endpoint in the parent class component in React. I pass this data to the child class component. The first time everything works fine but after a page refresh the data in the child component becomes undefined and the app crashes.
Here is the representation of the situation:
The ParentComponent
import React, { Component } from 'react'
import { gql } from "apollo-boost";
import {graphql} from 'react-apollo';
import ChildComponent from './ChildComponent'
const getProducts = gql`
{
category {
products {
id
name
gallery
}
}
}
`
class ParentComponent extends Component {
constructor(props) {
super(props)
this.state = {
products: []
}
}
componentDidMount() {
setTimeout(() => {
this.setState({
products: [...this.props.data.category.products]
})
}, 1000)
}
render () {
let products = this.state.products;
return (
<div><ChildComponent theProducts = {products}/></div>
)
}
}
export default graphql(getProducts)(ParentComponent);
The ChildComponent
import React, { Component } from 'react'
class ChildComponent extends Component {
constructor(props) {
super(props)
this.state = {
products: this.props.theProducts
}
}
render () {
let item = this.state.products.find(each => each.id === id);
return (
<div>
<ul>
<li>{item.name}</li>
<li><img src= {item.gallery[0]} alt="product"></img></li>
</ul>
</div>
)
}
}
export default ChildComponent;
So, when the app starts everything seems to work fine. But if I refresh the page it throws an error and says that name is undefined, gallery is undefined. It is clear that the data is not coming through to the ChildComponent. Is there a way to make sure that the data comes in at any time?
Thank you in advance.
You use theProducts in the ChildComponent but you pass theProduct from ParentComponent . And state product also has the same error. Just update to theProducts and product

How can I obtain class props from url and store in react-redux

so I am trying to pass params using route to a react component and also at the same time use Component class props. Here is what am doing
import { loadSchemes, } from '../../actions/schemes;
export class Schemes extends Component {
constructor(props) {
super(props);
const { match: { params } } = this.props;
this.state = {
client_id: params.pk,
}
}
componentDidMount() {
this.props.loadSchemes();
}
render(){
return(
<div>
{this.props.schemes_list.map((scheme,index)=><p key={index}>{scheme}</p>)}
</div>
)
}
}
const mapStateToProps = (state) => ({
schemes_list: state.schemes,
});
export default connect(mapStateToProps,{ loadSchemes,})(Schemes);
And I have a url to this component as
<Route path="/client/:pk/schemes" component={Schemes}/>
The problem is I get an error this.props.schemes_list is undefined and this.props.loadSchemes is undefined
please help am using react-redux
Obviousely in component from where you call Scheme, you import { Schemes }, an unconnected component, instead of Schemes - default connected component. Please check it.

React / Redux wait for store to update

I have a problem that a react component is rendering before the redux store has any data.
The problem is caused by the React component being rendered to the page before the existing angular app has dispatched the data to the store.
I cannot alter the order of the rendering or anything like that.
My simple React component is
import React, {Component} from 'react';
import { connect } from 'react-redux';
import {addBot} from './actions';
class FlowsContainer extends React.Component {
componentDidMount() {
this.props.initStoreWithBot();
}
render() {
// *** at this point I have the store in state prop
//but editorFlow array is not yet instanced, it's undefined
const tasks = this.props.state.editorFlow[0].flow.tasks
return (
<div>
Flow editor react component in main container
</div>
);
}
}
const mapStateToProps = (state) => ({
state : state
})
const mapDispatchToProps = (dispatch) => {
return {
initStoreWithBot : () => dispatch(addBot("test 123"))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(FlowsContainer)
So how can I hold off the rendering until editorFlow array has elements ?
You can use Conditional Rendering.
import {addBot} from './actions';
class FlowsContainer extends React.Component {
componentDidMount() {
this.props.initStoreWithBot();
}
render() {
// *** at this point I have the store in state prop
//but editorFlow array is not yet instanced, it's undefined
const { editorFlow } = this.props.state;
let tasks;
if (typeof editorFlow === 'object' && editorFlow.length > 0) {
tasks = editorFlow[0].flow.tasks;
}
return (
{tasks &&
<div>
Flow editor react component in main container
</div>
}
);
}
}
const mapStateToProps = (state) => ({
state : state
})
const mapDispatchToProps = (dispatch) => {
return {
initStoreWithBot : () => dispatch(addBot("test 123"))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(FlowsContainer)
As far as I know, you can't.
the way redux works is that it first renders everything, then actions take place with some async stuff(such as loading data), then the store gets populated, and then redux updates the components with the new state(using mapStateToProps).
the lifecycle as I understand it is this :
render the component with the initial state tree that's provided when you create the store.
Do async actions, load data, extend/modify the redux state
Redux updates your components with the new state.
I don't think mapping the entire redux state to a single prop is a good idea, the component should really take what it needs from the global state.
Adding some sane defaults to your component can ensure that a "loading" spinner is displayed until the data is fetched.
In response to Cssko (I've upped your answer) (and thedude) thanks guys a working solution is
import React, {Component} from 'react';
import { connect } from 'react-redux';
import {addBot} from './actions';
class FlowsContainer extends React.Component {
componentDidMount() {
this.props.initStoreWithBot();
}
render() {
const { editorFlow } = this.props.state;
let tasks;
if (typeof editorFlow === 'object' && editorFlow.length > 0) {
tasks = editorFlow[0].flow.tasks;
}
if(tasks){
return (
<div>
Flow editor react component in main container
</div>
)
}
else{
return null;
}
}
}
const mapStateToProps = (state) => ({
state : state
})
const mapDispatchToProps = (dispatch) => {
return {
initStoreWithBot : () => dispatch(addBot("test 123"))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(FlowsContainer)

React-Dates in component using Redux

As a newbie in React and Redux, i'm trying to use react-dates in a component.
This is my code:
import * as React from 'react';
import { connect } from 'react-redux';
import { ApplicationState } from '../store';
import * as DateState from '../store/Date';
import * as SingleDatePicker from 'react-dates';
type DateProps = DateState.DateState & typeof DateState.actionCreators;
class DatePickerSingle extends React.Component<DateProps, any> {
public render() {
let { date } = this.props;
return (
<div>
<SingleDatePicker
id="date_input"
date={this.props.date}
focused={this.state.focused}
onDateChange={(date) => { this.props.user({ date }); }}
onFocusChange={({ focused }) => { this.setState({ focused }); }}
isOutsideRange={() => false}
displayFormat="dddd LL">
</SingleDatePicker>
</div>
);
}
}
export default connect(
(state: ApplicationState) => state.date,
DateState.actionCreators
)(DatePickerSingle);
This returns the following error:
Exception: Call to Node module failed with error: TypeError: Cannot read property 'focused' of null
focused an onFocusChange should receive the "datepicker state" as far as I understand.
Docs:
onFocusChange is the callback necessary to update the focus state in
the parent component. It expects a single argument of the form {
focused: PropTypes.bool }.
I think the problem is that I inject the DateState in the DatePickerSingle component, which doesn't know about focused state.
Is it possible to use my "own" state and the state from the DatePicker together? Or what is the best approach?
I'm trying for quite a while now, and I hope someone can help me with this.
UPDATE
The answer is quite simple: this.state is null because it has not been initialized. Just add
constructor() {
super();
this.state = {
focused: false
}
}
Anything coming from redux will be passed to your component as props, you can have component state in addition to that.

Can't access React props modified by Redux MapStateToProps

Got undefined when trying to access this.props.state value
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';
const mapStateToProps = ({ movies }) => ({
state: movies,
});
class App extends Component {
componentDidMount() {
this.props.addMovie({ title: 'Movie' }); //redux action
}
render() {
const { state } = this.props;
console.log(state.test); //Object {title: "Movie"}
console.log(state.test.title); //Uncaught TypeError: Cannot read property 'title' of undefined
return (
<div>Hello {state.test.title}!</div> //doesn't work
);
}
}
export default connect(mapStateToProps, actions)(App);
After redux complete the action i've got state object in component props
I can access it from Chrome DevTools $r.props.state.test.title but can't access it from render function
For example I can get value from this.props.params.movieID but can't get any params modified by mapStateToProps
How can I put this.props.state.test.title value in my div?
Inside your render function check if the title is undefined because the render function is being called before your redux action is resolving. Once your state is updated and your component renders it should show up the second time.
render() {
const { state } = this.props;
console.log(state.test);
if(state.test && state.test.title){
console.log(state.test.title);
return (
<div>Hello {state.test.title}!</div>
)
} else {
return (
<div>No movies listed</div>
);
}
}

Resources