Learning react by coding,
in my component when it starts rendering in my console i'm getting(console.log) few times Book [] and after it i'm getting Book [{identifier: '1-1-1-1', name: 'Harry Potter'}, {identifier: '2-4-6-1', name: 'Narnia'}]
So first renders array has nothing in it, is there a way to check when array has something in it then go and take first identifier you find(then i will dispatch it) ?
any suggestions ?
my unsuccessful code:
const books = useSelector((state: RootStateOrAny) => state.library.books);
console.log("books", books.length > 0 && books[0]?.identifier)
dispatch(bookIdentifier("here i need to dispatch first identifier from list"));
CodePudding user response:
You can use useEffect
import { useEffect } from 'react'
const books = useSelector((state: RootStateOrAny) => state.library.books);
useEffect(() => {
if (books?.length > 0 && books?.[0]?.identifier) dispatch(bookIdentifier(books[0].identifier));
}, [books])