Ginger Bread
Ginger Bread

Reputation: 625

Set state of react component by using redux store

How I can assign some values of redux store to my component local state?

I should use redux actions to get data from API in my componentDidMount() method. Am I right? after getting data by redux I want to set my component's state using the data from redux store.I got an error this.props.article is undefined., but redux devtools shows that article object exists.

Where I supposed to call this.setState() method ??? I tried to call it in componentWillRecieveProps() or componentDidUpdate() , but unsuccessfuly. Please any help.Thank you in advance.

import React, { Component, Fragment } from 'react';
import { Typography,Spin } from 'antd';
import {connect} from 'react-redux';
import {getArticleDetails} from '../store/actions/articles';



class ArticleEdit extends Component {
    articleID = this.props.match.params.articleID; 
    state={

        str:'initial'
    }
    onChange = (str) => {
        console.log('Content change:', str);
        this.setState({ str1:str });

      };
    componentDidMount(){
        this.props.getArticleDetails(this.articleID);// GET data from api
        this.setState({str:this.props.article.title});// returns undefined

    }

    render() {
        return (
            <Fragment>
                {this.props.article===undefined?(<Spin/>):
                    (
                    <div>
                        <div style={{marginRight:'500px'}}>
                          <Paragraph editable={{ onChange: this.onChange}}>                          
                               {this.state.str}
                          </Paragraph>
                        </div>
                    </div>
                    )}    
            </Fragment>
        )
    }
}

const mapStateToProps = state =>({
    article: state.articleReducer.articles[0],    
})

export default connect(mapStateToProps,{getArticleDetails})(ArticleEdit);

Upvotes: 1

Views: 4547

Answers (1)

Cameron
Cameron

Reputation: 66

As Henrik said, you want to use this.props instead of this.state. You already retrieve an article using mapStateToProps, which is good. If you want to pass the article title to your component, you can add some code in your render() method, like so:

render() {
    const { article } = this.props
    const { title } = article
    return (
            ...
                      <Paragraph editable={{ onChange: this.onChange}}>                          
                           {title}
                      </Paragraph>
            ...

Upvotes: 5

Related Questions