0

I am using Context Hooks to work with states within react native. I would like to initialize the state via a async function doing an API call and then return the initial state via useState. Thats my try to set the initial state for "touristyOptions", however this does not work. I suspects its due to the async function?

**This is my Context/Provider**
    import React, { useState, useEffect } from "react";
import * as firebase from "firebase";
import { levelTables } from "../config/config";

const LevelOptionsContext = React.createContext();

const LevelOptionsProvider = (props) => {
  
  const setLevelOptions = (type) => {
    let categoryRef = firebase
      .database()
      .ref(type)
      .orderByKey();
    categoryRef
      .once("value")
      .then((snapshot) => {
        let result = [];
        snapshot.forEach(function(childSnapshot) {
          let value = childSnapshot.val();
          result.push({ value, active: false });
        });
        return [...result];
      })
      .catch((error) => console.log(error))
  };

  const [touristyOptions, setTouristyOptions] = useState(
    setLevelOptions("touristy_level")
  );
  const [adventurouseOptions, setAdventurouseOptions] = useState([]);

  return (
    <LevelOptionsContext.Provider
      value={{
        adventurouseOptions,
        setAdventurouseOptions,
        touristyOptions,
        setTouristyOptions
      }}
    >
      {props.children}
    </LevelOptionsContext.Provider>
  );
};

export { LevelOptionsContext, LevelOptionsProvider };
This does not work. Anyone can give a hint?

1 Answers1

1

Please try this.

import React, { useState, useEffect } from "react";
import * as firebase from "firebase";
import { levelTables } from "../config/config";

const LevelOptionsContext = React.createContext();

const LevelOptionsProvider = (props) => {
  const [touristyOptions, setTouristyOptions] = useState([]);
  const setLevelOptions = (type) => {
    let categoryRef = firebase
      .database()
      .ref(type)
      .orderByKey();
    categoryRef
      .once("value")
      .then((snapshot) => {
        let result = [];
        snapshot.forEach(function(childSnapshot) {
          let value = childSnapshot.val();
          result.push({ value, active: false });
        });
        setTouristOptions(result)
      })
      .catch((error) => console.log(error))
  };
  useEffect(() => { setLevelOptions(); }, []);
  return (
//    ...
  );
};
Daniel Zheng
  • 304
  • 1
  • 9