Cannot read property 'map' of undefined - react , redux












2















I'm trying to show a list of articles in my component and I'm getting "Cannot read property 'map' of undefined" error on my "articleList.js" component .what's wrong with my code ?
and also When I log articles , It's undefined.



I have below Code in my reducer :



 const initialState = {
articles: ,
loading: false,
error: null
};


export default (state=initialState, action) => {
switch (action.type) {
case GET_ARTICLES:
return {
...state,
articles: action.payload,
loading: false
};


code for action :



 export const getArticles =()=> dispatch =>{
fetch('http://localhost:8000/api/articles/')
.then(handleErrors)
.then(res => dispatch(
{
type : GET_ARTICLES,
payload: res.json
}
))}


code for component :



 componentDidMount() {
this.props.getArticles();
}

render() {
const { articles } = this.props.article;

return (
<div>
<div>
<div>
{articles.map(({ id, header }) => (
<div key={id} timeout={500} className="fade">
<div>
<button className="remove-btn" onClick={this.onDeleteClick.bind(this, id)} >Remove</button>
{header}
</div>
</div>
))}
</div>
</div>
</div>
);
}
}

const mapStateToProps = state => ({
article: state.article
});

export default connect(
mapStateToProps, { getArticles} )(ArticleList);


Sorry about the large amount of code dumped, its just all related and I believe the error lies somewhere within having an undefined initialState but I cant see what I have missed defining










share|improve this question

























  • your reducer saves the state inside articles, your payload reads it from article and your statemapper gets it from article, so which one is correct now? And your render gets it from this.props.article.articles? How is your data looking?

    – Icepickle
    Nov 24 '18 at 6:55













  • I have a combine reducer 'export default combineReducers({ article : articleReducer' }) and article is singular here.

    – Mary Qafarinia
    Nov 24 '18 at 6:56













  • You are however never checking if articles would be undefined (as you get it from a service, it will take a while to return, your component might have rendered already), so make sure you don't render while loading (or that you at least verify if articles is not undefined). Also your fetch, shouldn't it be res.json() instead of just res.json or is the handleErrors before that doing something we don't see? :)

    – Icepickle
    Nov 24 '18 at 6:58













  • Thank you I will check those points in a moment.

    – Mary Qafarinia
    Nov 24 '18 at 7:03


















2















I'm trying to show a list of articles in my component and I'm getting "Cannot read property 'map' of undefined" error on my "articleList.js" component .what's wrong with my code ?
and also When I log articles , It's undefined.



I have below Code in my reducer :



 const initialState = {
articles: ,
loading: false,
error: null
};


export default (state=initialState, action) => {
switch (action.type) {
case GET_ARTICLES:
return {
...state,
articles: action.payload,
loading: false
};


code for action :



 export const getArticles =()=> dispatch =>{
fetch('http://localhost:8000/api/articles/')
.then(handleErrors)
.then(res => dispatch(
{
type : GET_ARTICLES,
payload: res.json
}
))}


code for component :



 componentDidMount() {
this.props.getArticles();
}

render() {
const { articles } = this.props.article;

return (
<div>
<div>
<div>
{articles.map(({ id, header }) => (
<div key={id} timeout={500} className="fade">
<div>
<button className="remove-btn" onClick={this.onDeleteClick.bind(this, id)} >Remove</button>
{header}
</div>
</div>
))}
</div>
</div>
</div>
);
}
}

const mapStateToProps = state => ({
article: state.article
});

export default connect(
mapStateToProps, { getArticles} )(ArticleList);


Sorry about the large amount of code dumped, its just all related and I believe the error lies somewhere within having an undefined initialState but I cant see what I have missed defining










share|improve this question

























  • your reducer saves the state inside articles, your payload reads it from article and your statemapper gets it from article, so which one is correct now? And your render gets it from this.props.article.articles? How is your data looking?

    – Icepickle
    Nov 24 '18 at 6:55













  • I have a combine reducer 'export default combineReducers({ article : articleReducer' }) and article is singular here.

    – Mary Qafarinia
    Nov 24 '18 at 6:56













  • You are however never checking if articles would be undefined (as you get it from a service, it will take a while to return, your component might have rendered already), so make sure you don't render while loading (or that you at least verify if articles is not undefined). Also your fetch, shouldn't it be res.json() instead of just res.json or is the handleErrors before that doing something we don't see? :)

    – Icepickle
    Nov 24 '18 at 6:58













  • Thank you I will check those points in a moment.

    – Mary Qafarinia
    Nov 24 '18 at 7:03
















2












2








2








I'm trying to show a list of articles in my component and I'm getting "Cannot read property 'map' of undefined" error on my "articleList.js" component .what's wrong with my code ?
and also When I log articles , It's undefined.



I have below Code in my reducer :



 const initialState = {
articles: ,
loading: false,
error: null
};


export default (state=initialState, action) => {
switch (action.type) {
case GET_ARTICLES:
return {
...state,
articles: action.payload,
loading: false
};


code for action :



 export const getArticles =()=> dispatch =>{
fetch('http://localhost:8000/api/articles/')
.then(handleErrors)
.then(res => dispatch(
{
type : GET_ARTICLES,
payload: res.json
}
))}


code for component :



 componentDidMount() {
this.props.getArticles();
}

render() {
const { articles } = this.props.article;

return (
<div>
<div>
<div>
{articles.map(({ id, header }) => (
<div key={id} timeout={500} className="fade">
<div>
<button className="remove-btn" onClick={this.onDeleteClick.bind(this, id)} >Remove</button>
{header}
</div>
</div>
))}
</div>
</div>
</div>
);
}
}

const mapStateToProps = state => ({
article: state.article
});

export default connect(
mapStateToProps, { getArticles} )(ArticleList);


Sorry about the large amount of code dumped, its just all related and I believe the error lies somewhere within having an undefined initialState but I cant see what I have missed defining










share|improve this question
















I'm trying to show a list of articles in my component and I'm getting "Cannot read property 'map' of undefined" error on my "articleList.js" component .what's wrong with my code ?
and also When I log articles , It's undefined.



I have below Code in my reducer :



 const initialState = {
articles: ,
loading: false,
error: null
};


export default (state=initialState, action) => {
switch (action.type) {
case GET_ARTICLES:
return {
...state,
articles: action.payload,
loading: false
};


code for action :



 export const getArticles =()=> dispatch =>{
fetch('http://localhost:8000/api/articles/')
.then(handleErrors)
.then(res => dispatch(
{
type : GET_ARTICLES,
payload: res.json
}
))}


code for component :



 componentDidMount() {
this.props.getArticles();
}

render() {
const { articles } = this.props.article;

return (
<div>
<div>
<div>
{articles.map(({ id, header }) => (
<div key={id} timeout={500} className="fade">
<div>
<button className="remove-btn" onClick={this.onDeleteClick.bind(this, id)} >Remove</button>
{header}
</div>
</div>
))}
</div>
</div>
</div>
);
}
}

const mapStateToProps = state => ({
article: state.article
});

export default connect(
mapStateToProps, { getArticles} )(ArticleList);


Sorry about the large amount of code dumped, its just all related and I believe the error lies somewhere within having an undefined initialState but I cant see what I have missed defining







reactjs redux






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 6:59







Mary Qafarinia

















asked Nov 24 '18 at 6:51









Mary QafariniaMary Qafarinia

1721113




1721113













  • your reducer saves the state inside articles, your payload reads it from article and your statemapper gets it from article, so which one is correct now? And your render gets it from this.props.article.articles? How is your data looking?

    – Icepickle
    Nov 24 '18 at 6:55













  • I have a combine reducer 'export default combineReducers({ article : articleReducer' }) and article is singular here.

    – Mary Qafarinia
    Nov 24 '18 at 6:56













  • You are however never checking if articles would be undefined (as you get it from a service, it will take a while to return, your component might have rendered already), so make sure you don't render while loading (or that you at least verify if articles is not undefined). Also your fetch, shouldn't it be res.json() instead of just res.json or is the handleErrors before that doing something we don't see? :)

    – Icepickle
    Nov 24 '18 at 6:58













  • Thank you I will check those points in a moment.

    – Mary Qafarinia
    Nov 24 '18 at 7:03





















  • your reducer saves the state inside articles, your payload reads it from article and your statemapper gets it from article, so which one is correct now? And your render gets it from this.props.article.articles? How is your data looking?

    – Icepickle
    Nov 24 '18 at 6:55













  • I have a combine reducer 'export default combineReducers({ article : articleReducer' }) and article is singular here.

    – Mary Qafarinia
    Nov 24 '18 at 6:56













  • You are however never checking if articles would be undefined (as you get it from a service, it will take a while to return, your component might have rendered already), so make sure you don't render while loading (or that you at least verify if articles is not undefined). Also your fetch, shouldn't it be res.json() instead of just res.json or is the handleErrors before that doing something we don't see? :)

    – Icepickle
    Nov 24 '18 at 6:58













  • Thank you I will check those points in a moment.

    – Mary Qafarinia
    Nov 24 '18 at 7:03



















your reducer saves the state inside articles, your payload reads it from article and your statemapper gets it from article, so which one is correct now? And your render gets it from this.props.article.articles? How is your data looking?

– Icepickle
Nov 24 '18 at 6:55







your reducer saves the state inside articles, your payload reads it from article and your statemapper gets it from article, so which one is correct now? And your render gets it from this.props.article.articles? How is your data looking?

– Icepickle
Nov 24 '18 at 6:55















I have a combine reducer 'export default combineReducers({ article : articleReducer' }) and article is singular here.

– Mary Qafarinia
Nov 24 '18 at 6:56







I have a combine reducer 'export default combineReducers({ article : articleReducer' }) and article is singular here.

– Mary Qafarinia
Nov 24 '18 at 6:56















You are however never checking if articles would be undefined (as you get it from a service, it will take a while to return, your component might have rendered already), so make sure you don't render while loading (or that you at least verify if articles is not undefined). Also your fetch, shouldn't it be res.json() instead of just res.json or is the handleErrors before that doing something we don't see? :)

– Icepickle
Nov 24 '18 at 6:58







You are however never checking if articles would be undefined (as you get it from a service, it will take a while to return, your component might have rendered already), so make sure you don't render while loading (or that you at least verify if articles is not undefined). Also your fetch, shouldn't it be res.json() instead of just res.json or is the handleErrors before that doing something we don't see? :)

– Icepickle
Nov 24 '18 at 6:58















Thank you I will check those points in a moment.

– Mary Qafarinia
Nov 24 '18 at 7:03







Thank you I will check those points in a moment.

– Mary Qafarinia
Nov 24 '18 at 7:03














2 Answers
2






active

oldest

votes


















1














Seems yo confuse yourself with singular / plural variables' names. Your action sets articles as plural in reducers' state:



return {
...state,
articles: action.payload,


So when you mapStateToProps:



 const mapStateToProps = state => ({
article: state.article
});


state.article will be undefined as reducer never sets it as singular variable. Also from the snippet you provided I see no reason to use singular term anyway.



So try changing like:



  const { articles } = this.props.articles;

const mapStateToProps = state => ({
articles: state.articles
});





share|improve this answer
























  • Thank you , I made all articles plural and now it shows the initial state but when it wants to get data from service it shows "TypeError: articles.map is not a function" error

    – Mary Qafarinia
    Nov 24 '18 at 7:31











  • Because they come from an async call, you also need to check if they already exist - {articles && articles.map(...

    – Julius Dzidzevičius
    Nov 25 '18 at 7:35





















0














Well , i think you just need to check if your articles is undefined , the state update may be asynchronous, so at the first time the render method was called it was undefined , just do something like



{articles ? {articles.map(({ id, header }) => (
<div key={id} timeout={500} className="fade">
<div>
<button className="remove-btn" onClick={this.onDeleteClick.bind(this, id)} >Remove</button>
{header}
</div>
</div>
))} : null }





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455881%2fcannot-read-property-map-of-undefined-react-redux%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Seems yo confuse yourself with singular / plural variables' names. Your action sets articles as plural in reducers' state:



    return {
    ...state,
    articles: action.payload,


    So when you mapStateToProps:



     const mapStateToProps = state => ({
    article: state.article
    });


    state.article will be undefined as reducer never sets it as singular variable. Also from the snippet you provided I see no reason to use singular term anyway.



    So try changing like:



      const { articles } = this.props.articles;

    const mapStateToProps = state => ({
    articles: state.articles
    });





    share|improve this answer
























    • Thank you , I made all articles plural and now it shows the initial state but when it wants to get data from service it shows "TypeError: articles.map is not a function" error

      – Mary Qafarinia
      Nov 24 '18 at 7:31











    • Because they come from an async call, you also need to check if they already exist - {articles && articles.map(...

      – Julius Dzidzevičius
      Nov 25 '18 at 7:35


















    1














    Seems yo confuse yourself with singular / plural variables' names. Your action sets articles as plural in reducers' state:



    return {
    ...state,
    articles: action.payload,


    So when you mapStateToProps:



     const mapStateToProps = state => ({
    article: state.article
    });


    state.article will be undefined as reducer never sets it as singular variable. Also from the snippet you provided I see no reason to use singular term anyway.



    So try changing like:



      const { articles } = this.props.articles;

    const mapStateToProps = state => ({
    articles: state.articles
    });





    share|improve this answer
























    • Thank you , I made all articles plural and now it shows the initial state but when it wants to get data from service it shows "TypeError: articles.map is not a function" error

      – Mary Qafarinia
      Nov 24 '18 at 7:31











    • Because they come from an async call, you also need to check if they already exist - {articles && articles.map(...

      – Julius Dzidzevičius
      Nov 25 '18 at 7:35
















    1












    1








    1







    Seems yo confuse yourself with singular / plural variables' names. Your action sets articles as plural in reducers' state:



    return {
    ...state,
    articles: action.payload,


    So when you mapStateToProps:



     const mapStateToProps = state => ({
    article: state.article
    });


    state.article will be undefined as reducer never sets it as singular variable. Also from the snippet you provided I see no reason to use singular term anyway.



    So try changing like:



      const { articles } = this.props.articles;

    const mapStateToProps = state => ({
    articles: state.articles
    });





    share|improve this answer













    Seems yo confuse yourself with singular / plural variables' names. Your action sets articles as plural in reducers' state:



    return {
    ...state,
    articles: action.payload,


    So when you mapStateToProps:



     const mapStateToProps = state => ({
    article: state.article
    });


    state.article will be undefined as reducer never sets it as singular variable. Also from the snippet you provided I see no reason to use singular term anyway.



    So try changing like:



      const { articles } = this.props.articles;

    const mapStateToProps = state => ({
    articles: state.articles
    });






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 24 '18 at 7:22









    Julius DzidzevičiusJulius Dzidzevičius

    4,83641945




    4,83641945













    • Thank you , I made all articles plural and now it shows the initial state but when it wants to get data from service it shows "TypeError: articles.map is not a function" error

      – Mary Qafarinia
      Nov 24 '18 at 7:31











    • Because they come from an async call, you also need to check if they already exist - {articles && articles.map(...

      – Julius Dzidzevičius
      Nov 25 '18 at 7:35





















    • Thank you , I made all articles plural and now it shows the initial state but when it wants to get data from service it shows "TypeError: articles.map is not a function" error

      – Mary Qafarinia
      Nov 24 '18 at 7:31











    • Because they come from an async call, you also need to check if they already exist - {articles && articles.map(...

      – Julius Dzidzevičius
      Nov 25 '18 at 7:35



















    Thank you , I made all articles plural and now it shows the initial state but when it wants to get data from service it shows "TypeError: articles.map is not a function" error

    – Mary Qafarinia
    Nov 24 '18 at 7:31





    Thank you , I made all articles plural and now it shows the initial state but when it wants to get data from service it shows "TypeError: articles.map is not a function" error

    – Mary Qafarinia
    Nov 24 '18 at 7:31













    Because they come from an async call, you also need to check if they already exist - {articles && articles.map(...

    – Julius Dzidzevičius
    Nov 25 '18 at 7:35







    Because they come from an async call, you also need to check if they already exist - {articles && articles.map(...

    – Julius Dzidzevičius
    Nov 25 '18 at 7:35















    0














    Well , i think you just need to check if your articles is undefined , the state update may be asynchronous, so at the first time the render method was called it was undefined , just do something like



    {articles ? {articles.map(({ id, header }) => (
    <div key={id} timeout={500} className="fade">
    <div>
    <button className="remove-btn" onClick={this.onDeleteClick.bind(this, id)} >Remove</button>
    {header}
    </div>
    </div>
    ))} : null }





    share|improve this answer




























      0














      Well , i think you just need to check if your articles is undefined , the state update may be asynchronous, so at the first time the render method was called it was undefined , just do something like



      {articles ? {articles.map(({ id, header }) => (
      <div key={id} timeout={500} className="fade">
      <div>
      <button className="remove-btn" onClick={this.onDeleteClick.bind(this, id)} >Remove</button>
      {header}
      </div>
      </div>
      ))} : null }





      share|improve this answer


























        0












        0








        0







        Well , i think you just need to check if your articles is undefined , the state update may be asynchronous, so at the first time the render method was called it was undefined , just do something like



        {articles ? {articles.map(({ id, header }) => (
        <div key={id} timeout={500} className="fade">
        <div>
        <button className="remove-btn" onClick={this.onDeleteClick.bind(this, id)} >Remove</button>
        {header}
        </div>
        </div>
        ))} : null }





        share|improve this answer













        Well , i think you just need to check if your articles is undefined , the state update may be asynchronous, so at the first time the render method was called it was undefined , just do something like



        {articles ? {articles.map(({ id, header }) => (
        <div key={id} timeout={500} className="fade">
        <div>
        <button className="remove-btn" onClick={this.onDeleteClick.bind(this, id)} >Remove</button>
        {header}
        </div>
        </div>
        ))} : null }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 24 '18 at 7:17









        Zaidoune MaherZaidoune Maher

        112




        112






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455881%2fcannot-read-property-map-of-undefined-react-redux%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            Refactoring coordinates for Minecraft Pi buildings written in Python