Create a React component for each element on JSON












1















I need consultation with rendering React components for each element in JSON (in this case - Firebase database).
I'm trying to create an array of book's data and push it to an array bookKeysArray which then I will use for mapping.



As a result I get error that component ListOfUserBooks doesn't return anything (bookComponent is undefined).



Does anyone have any suggestions?



function ListOfUserBooks(props) {
currentUserId = firebase.auth().currentUser.uid;
userBooksDataRef = firebase.database().ref('booksData/').child(currentUserId);
let bookKeysArray = ,
bookComponent;

userBooksDataRef.once('value')
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
bookKey = childSnapshot.key;
bookData = childSnapshot.val();
description = bookData.description;
...

let bookDataArray = [description, ...];
bookKeysArray.push(bookDataArray);

bookComponent = bookKeysArray.map((book, index) => {
<ListOfUserBooks_ListView key = {index}
description = {book.description}
.../>
});
}
});
});
return bookComponent;
};


Firebase data structure



enter image description here










share|improve this question

























  • Could you provide an example of the data/data-structure?

    – JO3-W3B-D3V
    Dec 28 '18 at 23:54






  • 1





    This seems to be an async problem. bookComponent is returned before it is assigned within the then function. Could possibly be solved by using async/await (javascript.info/async-await) rather than callbacks.

    – Michael Hilus
    Dec 28 '18 at 23:56













  • I don't think Render functions are allowed to be aysnc. That's why all React docs suggest loading data in componentDidMount and then updating state on success to cause a re-render.

    – Matthew Herbst
    Dec 29 '18 at 0:06
















1















I need consultation with rendering React components for each element in JSON (in this case - Firebase database).
I'm trying to create an array of book's data and push it to an array bookKeysArray which then I will use for mapping.



As a result I get error that component ListOfUserBooks doesn't return anything (bookComponent is undefined).



Does anyone have any suggestions?



function ListOfUserBooks(props) {
currentUserId = firebase.auth().currentUser.uid;
userBooksDataRef = firebase.database().ref('booksData/').child(currentUserId);
let bookKeysArray = ,
bookComponent;

userBooksDataRef.once('value')
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
bookKey = childSnapshot.key;
bookData = childSnapshot.val();
description = bookData.description;
...

let bookDataArray = [description, ...];
bookKeysArray.push(bookDataArray);

bookComponent = bookKeysArray.map((book, index) => {
<ListOfUserBooks_ListView key = {index}
description = {book.description}
.../>
});
}
});
});
return bookComponent;
};


Firebase data structure



enter image description here










share|improve this question

























  • Could you provide an example of the data/data-structure?

    – JO3-W3B-D3V
    Dec 28 '18 at 23:54






  • 1





    This seems to be an async problem. bookComponent is returned before it is assigned within the then function. Could possibly be solved by using async/await (javascript.info/async-await) rather than callbacks.

    – Michael Hilus
    Dec 28 '18 at 23:56













  • I don't think Render functions are allowed to be aysnc. That's why all React docs suggest loading data in componentDidMount and then updating state on success to cause a re-render.

    – Matthew Herbst
    Dec 29 '18 at 0:06














1












1








1








I need consultation with rendering React components for each element in JSON (in this case - Firebase database).
I'm trying to create an array of book's data and push it to an array bookKeysArray which then I will use for mapping.



As a result I get error that component ListOfUserBooks doesn't return anything (bookComponent is undefined).



Does anyone have any suggestions?



function ListOfUserBooks(props) {
currentUserId = firebase.auth().currentUser.uid;
userBooksDataRef = firebase.database().ref('booksData/').child(currentUserId);
let bookKeysArray = ,
bookComponent;

userBooksDataRef.once('value')
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
bookKey = childSnapshot.key;
bookData = childSnapshot.val();
description = bookData.description;
...

let bookDataArray = [description, ...];
bookKeysArray.push(bookDataArray);

bookComponent = bookKeysArray.map((book, index) => {
<ListOfUserBooks_ListView key = {index}
description = {book.description}
.../>
});
}
});
});
return bookComponent;
};


Firebase data structure



enter image description here










share|improve this question
















I need consultation with rendering React components for each element in JSON (in this case - Firebase database).
I'm trying to create an array of book's data and push it to an array bookKeysArray which then I will use for mapping.



As a result I get error that component ListOfUserBooks doesn't return anything (bookComponent is undefined).



Does anyone have any suggestions?



function ListOfUserBooks(props) {
currentUserId = firebase.auth().currentUser.uid;
userBooksDataRef = firebase.database().ref('booksData/').child(currentUserId);
let bookKeysArray = ,
bookComponent;

userBooksDataRef.once('value')
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
bookKey = childSnapshot.key;
bookData = childSnapshot.val();
description = bookData.description;
...

let bookDataArray = [description, ...];
bookKeysArray.push(bookDataArray);

bookComponent = bookKeysArray.map((book, index) => {
<ListOfUserBooks_ListView key = {index}
description = {book.description}
.../>
});
}
});
});
return bookComponent;
};


Firebase data structure



enter image description here







javascript json reactjs firebase






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 29 '18 at 0:02







Ivan Burzakovskiy

















asked Dec 28 '18 at 23:52









Ivan BurzakovskiyIvan Burzakovskiy

859




859













  • Could you provide an example of the data/data-structure?

    – JO3-W3B-D3V
    Dec 28 '18 at 23:54






  • 1





    This seems to be an async problem. bookComponent is returned before it is assigned within the then function. Could possibly be solved by using async/await (javascript.info/async-await) rather than callbacks.

    – Michael Hilus
    Dec 28 '18 at 23:56













  • I don't think Render functions are allowed to be aysnc. That's why all React docs suggest loading data in componentDidMount and then updating state on success to cause a re-render.

    – Matthew Herbst
    Dec 29 '18 at 0:06



















  • Could you provide an example of the data/data-structure?

    – JO3-W3B-D3V
    Dec 28 '18 at 23:54






  • 1





    This seems to be an async problem. bookComponent is returned before it is assigned within the then function. Could possibly be solved by using async/await (javascript.info/async-await) rather than callbacks.

    – Michael Hilus
    Dec 28 '18 at 23:56













  • I don't think Render functions are allowed to be aysnc. That's why all React docs suggest loading data in componentDidMount and then updating state on success to cause a re-render.

    – Matthew Herbst
    Dec 29 '18 at 0:06

















Could you provide an example of the data/data-structure?

– JO3-W3B-D3V
Dec 28 '18 at 23:54





Could you provide an example of the data/data-structure?

– JO3-W3B-D3V
Dec 28 '18 at 23:54




1




1





This seems to be an async problem. bookComponent is returned before it is assigned within the then function. Could possibly be solved by using async/await (javascript.info/async-await) rather than callbacks.

– Michael Hilus
Dec 28 '18 at 23:56







This seems to be an async problem. bookComponent is returned before it is assigned within the then function. Could possibly be solved by using async/await (javascript.info/async-await) rather than callbacks.

– Michael Hilus
Dec 28 '18 at 23:56















I don't think Render functions are allowed to be aysnc. That's why all React docs suggest loading data in componentDidMount and then updating state on success to cause a re-render.

– Matthew Herbst
Dec 29 '18 at 0:06





I don't think Render functions are allowed to be aysnc. That's why all React docs suggest loading data in componentDidMount and then updating state on success to cause a re-render.

– Matthew Herbst
Dec 29 '18 at 0:06












1 Answer
1






active

oldest

votes


















1














The execution of the .then is asynchronous. So you are actually returning bookComponent before having even populated it. In react development operations such retrieving data from FireBase are executed in a lifecycle hook to populate the state and then render it. You can easily accomplish this using a class component:



class ListOfUserBooks extends React.Component {
constructor(...args) {
super(...args)
this.state = { bookKeysArray: }
}

componentDidMount() {
currentUserId = firebase.auth().currentUser.uid;
userBooksDataRef = firebase.database().ref('booksData/').child(currentUserId);
userBooksDataRef.once('value')
.then((snapshot) => {
bookKeysArray =
snapshot.forEach((childSnapshot) => {
bookKey = childSnapshot.key;
bookData = childSnapshot.val();
description = bookData.description;
...
bookKeysArray.push([description, ...]);
})
this.setState({ bookKeysArray })
}

render() {
return this.state.bookKeysArray.map((book, index) => {
return <ListOfUserBooks_ListView key = {index} .../>
});
}
}





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%2f53965525%2fcreate-a-react-component-for-each-element-on-json%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    The execution of the .then is asynchronous. So you are actually returning bookComponent before having even populated it. In react development operations such retrieving data from FireBase are executed in a lifecycle hook to populate the state and then render it. You can easily accomplish this using a class component:



    class ListOfUserBooks extends React.Component {
    constructor(...args) {
    super(...args)
    this.state = { bookKeysArray: }
    }

    componentDidMount() {
    currentUserId = firebase.auth().currentUser.uid;
    userBooksDataRef = firebase.database().ref('booksData/').child(currentUserId);
    userBooksDataRef.once('value')
    .then((snapshot) => {
    bookKeysArray =
    snapshot.forEach((childSnapshot) => {
    bookKey = childSnapshot.key;
    bookData = childSnapshot.val();
    description = bookData.description;
    ...
    bookKeysArray.push([description, ...]);
    })
    this.setState({ bookKeysArray })
    }

    render() {
    return this.state.bookKeysArray.map((book, index) => {
    return <ListOfUserBooks_ListView key = {index} .../>
    });
    }
    }





    share|improve this answer




























      1














      The execution of the .then is asynchronous. So you are actually returning bookComponent before having even populated it. In react development operations such retrieving data from FireBase are executed in a lifecycle hook to populate the state and then render it. You can easily accomplish this using a class component:



      class ListOfUserBooks extends React.Component {
      constructor(...args) {
      super(...args)
      this.state = { bookKeysArray: }
      }

      componentDidMount() {
      currentUserId = firebase.auth().currentUser.uid;
      userBooksDataRef = firebase.database().ref('booksData/').child(currentUserId);
      userBooksDataRef.once('value')
      .then((snapshot) => {
      bookKeysArray =
      snapshot.forEach((childSnapshot) => {
      bookKey = childSnapshot.key;
      bookData = childSnapshot.val();
      description = bookData.description;
      ...
      bookKeysArray.push([description, ...]);
      })
      this.setState({ bookKeysArray })
      }

      render() {
      return this.state.bookKeysArray.map((book, index) => {
      return <ListOfUserBooks_ListView key = {index} .../>
      });
      }
      }





      share|improve this answer


























        1












        1








        1







        The execution of the .then is asynchronous. So you are actually returning bookComponent before having even populated it. In react development operations such retrieving data from FireBase are executed in a lifecycle hook to populate the state and then render it. You can easily accomplish this using a class component:



        class ListOfUserBooks extends React.Component {
        constructor(...args) {
        super(...args)
        this.state = { bookKeysArray: }
        }

        componentDidMount() {
        currentUserId = firebase.auth().currentUser.uid;
        userBooksDataRef = firebase.database().ref('booksData/').child(currentUserId);
        userBooksDataRef.once('value')
        .then((snapshot) => {
        bookKeysArray =
        snapshot.forEach((childSnapshot) => {
        bookKey = childSnapshot.key;
        bookData = childSnapshot.val();
        description = bookData.description;
        ...
        bookKeysArray.push([description, ...]);
        })
        this.setState({ bookKeysArray })
        }

        render() {
        return this.state.bookKeysArray.map((book, index) => {
        return <ListOfUserBooks_ListView key = {index} .../>
        });
        }
        }





        share|improve this answer













        The execution of the .then is asynchronous. So you are actually returning bookComponent before having even populated it. In react development operations such retrieving data from FireBase are executed in a lifecycle hook to populate the state and then render it. You can easily accomplish this using a class component:



        class ListOfUserBooks extends React.Component {
        constructor(...args) {
        super(...args)
        this.state = { bookKeysArray: }
        }

        componentDidMount() {
        currentUserId = firebase.auth().currentUser.uid;
        userBooksDataRef = firebase.database().ref('booksData/').child(currentUserId);
        userBooksDataRef.once('value')
        .then((snapshot) => {
        bookKeysArray =
        snapshot.forEach((childSnapshot) => {
        bookKey = childSnapshot.key;
        bookData = childSnapshot.val();
        description = bookData.description;
        ...
        bookKeysArray.push([description, ...]);
        })
        this.setState({ bookKeysArray })
        }

        render() {
        return this.state.bookKeysArray.map((book, index) => {
        return <ListOfUserBooks_ListView key = {index} .../>
        });
        }
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 29 '18 at 0:08









        Nicolò FuccellaNicolò Fuccella

        262




        262






























            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%2f53965525%2fcreate-a-react-component-for-each-element-on-json%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

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas