score:1

Accepted answer

you should move your settodos in useeffect

useeffect(() => {
    dbtodos.get().then((snapshot) => {
        const initialstate = [];    // also this you can move here

        snapshot.foreach((doc) => {
            const currenttodo = doc.data();
            currenttodo['id'] = doc.id;
            initialstate.push(currenttodo);
        });

        settodos(initialstate);   /// here
    });
}, []);

score:0

when you setstate in useeffect then you have to add setstate in dependency. instead of doing that use another arrow function and call it from useeffect.

use the code below

const app = () => {

// todos are the only state in app
const [ todos, settodos ] = usestate([]);

// fetches todos from firestore database on load
const fetchdata = () => {
    const initialstate = [];
    dbtodos.get().then((snapshot) => {
        snapshot.foreach((doc) => {
            const currenttodo = doc.data();
            currenttodo['id'] = doc.id;
            initialstate.push(currenttodo);
        });
    });
    settodos(initialstate);
}

useeffect(() => {
  fetchdata();
}, []);

// add todo
const addtodo = (title) => {
    const newtodo = {
        title     : title,
        completed : false
    };
    dbtodos.add(newtodo).then((doc) => {
        newtodo['id'] = doc.id;
        settodos([ ...todos, newtodo ]);
    });
};

score:0

in useeffect you create empty array. make a request. set empty array to state. when request was fulfilled you make changes in the array by ref. therefore you see you array in dev tool and react does'n rerender you component.

const app = () => {

// todos are the only state in app
const [ todos, settodos ] = usestate([]);

// fetches todos from firestore database on load
useeffect(() => {
    dbtodos.get().then((snapshot) => {
        settodos(snapshot.map((doc) => ({
          id: doc.id,
          ...doc.data(),
        })));
    });
}, []);

// add todo
const addtodo = (title) => {
    const newtodo = {
        title     : title,
        completed : false
    };
    dbtodos.add(newtodo).then((doc) => {
        newtodo['id'] = doc.id;
        settodos([ ...todos, newtodo ]);
    });
};


Related Query

More Query from same tag