Home > Enterprise >  useEffect didnt run
useEffect didnt run

Time:08-27

So i have this function that i want to run once when the app start. This function task is to create userId then i will run another function to fetch data from firebase with the userId that created before. But the fetch function didn't start or it didnt do the task well, there is no sign of error, that's what make it more confusing. If i press the fetch function by button it work correctly.

the state

  const [task, setTask] = useState(); // bisa di sebut sebagai controller text input
  const [taskItems, setTaskItems] = useState([]); // state untuk list task
  const [userId, setUserId] = useState();
      const [isLoading, setIsLoading] = useState(true);
 const baseUrl =
    'https://react-http-post-RANDOM_KEY-default-rtdb.firebaseio.com/task/'   userId;

this is function to create userId function on init app

    const handleCreateUser = async () => {
    setIsLoading(true);
    try {
      const value = await AsyncStorage.getItem('userId');
      if (value !== null) {
        setUserId(value);
      } else {
        const uniqueId = makeid(6);
        await AsyncStorage.setItem('userId', 'user'   uniqueId);
        setUserId('user'   uniqueId);
      }
    await  fetchDatabase();
    } catch (error) {
      console.log('errorrr AsyncStorage'   error);
    }
    setIsLoading(false);
  };

this is function to fetch data from firebase

    const fetchDatabase = async () => {
    console.log('infinite looping');
    try {
      const response = await fetch(baseUrl   '.json');
      if (!response.ok) {
        throw new Error('Something went wrong!');
      }

      const data = await response.json();

      // looping Map/Object dengan key sebagai indexnya
      const loadedTask = [];
      for (var id in data) {
        loadedTask.push({
          key: id,
          text: data[id].text,
          isComplete: data[id].isComplete,
        });
      }
      setTaskItems(loadedTask);
    } catch (error) {
      setError(error.message);
    }
  };

this is how i call the useEffect

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

CodePudding user response:

The first thing I see is that you are not using await correctly. It should be before fetchDatabase(); function that is inside handleCreateUser like so:

  await fetchDatabase();

The word await is there when you have to call an asynchronous function and you have to wait for this function to be completed.

Edit

To use only one useEffect you can check if your fetch function received your data by:

  // or whatever statusCode you get when the data are present
  if(reponse.statusCode === 200) {


      // the await is not needed because it is present for the reponse abov
      const data = response.json();
  
  
      // looping Map/Object dengan key sebagai indexnya

     const loadedTask = [];

       for (var id in data) {
         loadedTask.push({
           key: id,
           text: data[id].text,
           isComplete: data[id].isComplete,
        });
       }
       setTaskItems(loadedTask);
      }

CodePudding user response:

i got the answer, by using 2 useEffect

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

  useEffect(() => {
    fetchDatabase();
  }, [userId]);
  • Related