Home > OS >  How do I make useState hook work with my function?
How do I make useState hook work with my function?

Time:11-25

I am trying to execute a function to update a setState but it as well needs other state to load first.

    const [chatsIds, setChatsIds] = useState([]);
    const [chats, setChats] = useState([]);

    useEffect(() => {
        getChatsIds();
    }, []);

    useEffect(() => {
        getChats();
    }, [chats]);

the "getChats" needs the value from "chatsIds" but when the screen is loaded the value isn't , only when i reload the app again it gets the value.

Here are the functions :

    const getChatsIds = async () => {
        const ids = await getDoc(userRef, "chats");
        setChatsIds(ids);
    }

    const getChats = async () => {
        const chatsArr = [];

        chatsIds.forEach(async (id) => {
            const chat = await getDoc(doc(db, "Chats", id));
            chatsArr.push(chat);
            console.log(chatsArr);
        });

        setChats(chatsArr);
    }   

I've tried with the useEffect and useLayoutEffect hooks, with promises and async functions, but i haven't found what i'm doing wrong :(

CodePudding user response:

The problem is in your useEffect hook dependency. It should depends on chatsIds not chats.

useEffect(() => {
    getChats();
}, [chatsIds]);

Which mean fetching chatsIds should depend on first mount and fetching chats should depend on if chatsIds is chnaged.

CodePudding user response:

You simply change the useEffect hook to like below.

useEffect(() => {
  getChatsIds();
}, [chatsIds]);

CodePudding user response:

I Think getChat() is depend on chatIds...

so you use useEffect with chatIds on dependency

const [chatsIds, setChatsIds] = useState([]);
const [chats, setChats] = useState([]);

useEffect(() => {
    getChatsIds();
}, []);

useEffect(() => {
    getChats(chatsIds);
}, [chatsIds]);

const getChatsIds = async () => {
    const ids = await getDoc(userRef, "chats");
    setChatsIds(ids);
}

const getChats = async (chatsIds) => {
    const chatsArr = [];

    chatsIds.forEach(async (id) => {
        const chat = await getDoc(doc(db, "Chats", id));
        chatsArr.push(chat);
        console.log(chatsArr);
    });

    setChats(chatsArr);
}   
  • Related