Fred Osei
Fred Osei

Reputation: 45

React Hook useEffect does not render on mount, after navigating to next page (React Native)

both do not render on mount, I am trying to get the token from secure store and pass that token as the API Token, after I want to "getCompany" function to render and get a response from the API

const [token, setToken] = useState(null);
const [companyTypeList, setCompanyTypeList] = useState([]);

useEffect(() => {
    SecureStore.getItemAsync("user")
      .then((res) => {
        if (res) {
          let resObject = JSON.parse(res);
          console.log(resObject.token);
          setToken(resObject.token);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  useEffect(() => {
    axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
    const getCompanyType = () => {
      axios
        .get("/company/types")
        .then((response) => {
          const companyTypeArray = response.data.data;
          console.log("company types", response.data.data);
          setCompanyTypeList(companyTypeArray);
        })
        .catch((err) => {
          console.log(err.response.status);
          console.log("company types", err.response.data.message);
        });
    };
    getCompanyType();
    console.log(companyTypeList);
  }, []); ```

Upvotes: 2

Views: 2648

Answers (2)

Drew Reese
Drew Reese

Reputation: 202667

The useEffect hook is guaranteed to run after the initial render, when the component mounts, it will run at least once. getCompanyType runs asynchronous code, so the console.log(companyTypeList); will only log the initial state since state won't have updated by then.

I suggest using a single useEffect and pass the token to the GET request.

useEffect(() => {
  const getCompanyType = async () => {
    try {
      const token = await SecureStore.getItemAsync("user");

      // set the token state if you need need it for anything else later
      setToken(token);

      axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
    
      const response = await axios.get("/company/types");
      const companyTypeArray = response.data.data;
      setCompanyTypeList(companyTypeArray);
    } catch(err){
      if (err.response) {
        console.log(err.response.status);
        console.log("company types", err.response.data.message);
      } else {
        console.error(err);
      }
    };
  };

  getCompanyType();
}, []);

Upvotes: 2

lam
lam

Reputation: 565

try this:

  const getToken = useCallback(async () => {
    const res = await SecureStore.getItemAsync("user")
    return JSON.parse(res).token;
  }, []);

  useEffect(() => {
    const getCompanyType = async () => {
      const token = await getToken();
      axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
      const data = await axios
        .get("/company/types")
        .then((response) => {
          return response.data.data;
        })
        .catch((err) => {
          console.log(err.response.status);
          console.log("company types", err.response.data.message);
        });
        setCompanyTypeList(data);
        console.log(data);
      };
    getCompanyType();
  }, [getToken]);

Upvotes: 0

Related Questions