Lo que estoy tratando de lograr:
Recuperar book -> tomar book.chapterIds[0] para actualizar currentChapter -> tomar capítulo currentChapter para actualizar chapters
Estoy usando una variable de estado (Libro) para establecer otra variable de estado (capítulos), así:
useEffect(() => { getBook(match.params.id); // eslint-disable-next-line }, []); useEffect(() => { setCurrentChapter(book.chapterIds[0]); // eslint-disable-next-line }, [book]); useEffect(() => { getChapter(currentChapter); // eslint-disable-next-line }, [currentChapter]); Para el segundo efecto de uso, termino obteniendo: Uncaught TypeError: book.chapterIds is undefined
Esto es lo que probé:
useEffect(() => { if (Object.keys(book).length !== 0) { setCurrentChapter(book.chapterIds[0]); } // eslint-disable-next-line }, [book]);que funciona un poco, pero todavía termino activando:
useEffect(() => { getChapter(currentChapter); // eslint-disable-next-line }, [currentChapter]);donde tanto el libro como el capítulo actual no están definidos
Aplicación.js
const [book, setBook] = useState({}); const [chapters, setChapters] = useState({}); const [currentChapter, setCurrentChapter] = useState(); const [loading, setLoading] = useState(false); const getBook = async (id) => { setLoading(true); const res = await axios.get(`<someurl><with id>`); console.log(res.data); setBook(res.data.book); setLoading(false); }; const getChapter = async (chapterId) => { if (chapters[chapterId] === undefined) { console.log(`<someurl><with id & chapterId>`); setLoading(true); const res = await axios.get( `<someurl><with id & chapterId>` ); setLoading(false); console.log(res.data); setChapters({ ...chapters, [chapterId]: res.data.chapter, }); } };Libro.js
useEffect(() => { getBook(match.params.id); // eslint-disable-next-line }, []); useEffect(() => { if (Object.keys(book).length !== 0) { setCurrentChapter(book.chapterIds[0]); } // eslint-disable-next-line }, [book]); useEffect(() => { getChapter(currentChapter); // eslint-disable-next-line }, [currentChapter]); Además, obtengo book.chapterIds como indefinido al usarlo dentro del componente Book return()
¿Qué estoy haciendo mal?
Intente establecer todos los estados iniciales como nulos:
const [book, setBook] = useState(null); const [chapters, setChapters] = useState(null); const [currentChapter, setCurrentChapter] = useState(null);Entonces su useEffects:
useEffect(() => { getBook(match.params.id); // eslint-disable-next-line }, []); useEffect(() => { if(book && book.chapterIds?.length > 0) setCurrentChapter(book.chapterIds[0]); // eslint-disable-next-line }, [book]); useEffect(() => { if(currentChapter) getChapter(currentChapter); // eslint-disable-next-line }, [currentChapter]);