Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React – updated state observed with useSelector() doesn't render new components

I’m using Redux Toolkit and Redux Thunk. I successfully get my data asynchronously from a data source back into my component. Inside my component, I can observe the data coming with useSelector: const booksData = useSelector((state) => state.books);

At this point, I would like to loop the books I’m getting and render my Book component for each book data I’m getting:

  const renderBooks = (books) => {
    books.map((book) => {
      console.log(book.id);
      <Book props={book}/>;
    });
  };

Problem is, I can see this renderBooks is called and bookIds logged for each book. The <Book> component is not rendered though.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Am I missing something obvious? Isn’t the useSelector a state like useState so it should trigger rendering once updated?

Thanks in advance.

Rendering code (simplified to cut noise):

  return (
    <React.Fragment>

{/*some usual HTML here */}

      <div>{renderBooks(booksData.books)}</div>
    </React.Fragment>
  );

>Solution :

You need to return the values:

  const renderBooks = (books) => {
  return  books.map((book, index) => {
      console.log(book.id);
     return <Book key={index} props={book}/>;
    });
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading