본문 바로가기
Project/Rate My Resident

4. Using Variables in useEffect (useEffect에서 변수 쓰기)

by 빠니몽 2023. 3. 16.

03.16.2023

0. Background

What I wanted to do was to use the prop as name for components and fetching data from database when props was passed in the result page from the main page. Here is what I did.

1. Store the prop as name using useState

function Result(props){
    const [name, setName] = useState(null);
    
    // Set name using useEffect
    useEffect(()=>{
        if(location.state === null)
        	setName(props.name);
    	else
        	setName(location.state.name);
    }, []);
    return (
    	<>
        	{name}
        </>
    );
}

Since I used both ReatRoute and useNavigate for a reason, I made the conditional statement.

And then, I tried fetching data using name.

2. Fetch data with the variable

function Result(props){
    const [name, setName] = useState(null);
    
    useEffect(()=>{
        if(location.state === null)
        	setName(props.name);
    	else
        	setName(location.state.name);
    }, []);
    
    // Use name to fetch data from database when name set
    useEffect(()=>{
        const fetchData = async () => {
            const res = await fetch('your/api/url', {
                method: 'POST',
                mode: 'cors',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({"name": name})
            });
            
            const result = await res.json();
            result.forEach(r => {
                console.log(r);
            });
        };
        
        fetchData();
    }, [name]);
    
    return (
    	<>
        	{name}
        </>
    );
}

The thing here is pssing name variable as the second argument for the second useEffect. In another word, the second useEffect hook now depends on the variable, name. Thus, it will only work when name is set to non-null. Also, it will only re-run when the value of name changes as well.