Home > Net >  React - updated state observed with useSelector() doesn't render new components
React - updated state observed with useSelector() doesn't render new components

Time:10-01

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.

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>
  );

CodePudding user response:

You need to return the values:

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