Toh*_*awk 4 asynchronous reactjs react-context react-hooks use-effect
im trying to create an api request with the header value, that is received from a context component. However, as soon as the page component is loaded, it throws an Cannot read property '_id' of null exception. Is there a way to run the useEffect function, as soon as the context is loaded?
main component:
import React, { useState, useEffect, useContext } from "react";
import "./overview.scss";
/* COMPONENTS */;
import axios from 'axios';
import { GlobalContext } from '../../components/context/global';
const Overview = () => {
const [bookings, setBookings] = useState([]);
const [loaded, setLoaded] = useState(false);
const [user, setUser] = useContext(GlobalContext);
useEffect(() => {
axios
.get(`/api/v1/bookings/user/${user._id}`)
.then(res => setBookings(res.data))
.catch(err => console.log(err))
.finally(() => setLoaded(true));
}, [user]);
Run Code Online (Sandbox Code Playgroud)
context component:
import React, {useState, useEffect, createContext} from 'react';
import jwt from 'jsonwebtoken';
/* GLOBAL VARIABLES (CLIENT) */
export const GlobalContext = createContext();
export const GlobalProvider = props => {
/* ENVIRONMENT API URL */
const [user, setUser] = useState([]);
useEffect(() => {
const getSession = async () => {
const user = await sessionStorage.getItem('authorization');
setUser(jwt.decode(user));
}
getSession();
}, [])
return (
<GlobalContext.Provider value={[user, setUser]}>
{props.children}
</GlobalContext.Provider>
);
};
Run Code Online (Sandbox Code Playgroud)
这里的问题是useEffect在 mount 上运行,而您还没有用户。您只需要防范这种情况
useEffect(() => {
if (!user) return;
// use user._id
},[user])
Run Code Online (Sandbox Code Playgroud)
自然地,当 Context 获取用户时,它应该强制重新渲染您的组件,并且useEffect随着依赖项的变化自然应该重新运行。
| 归档时间: |
|
| 查看次数: |
4553 次 |
| 最近记录: |