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.
'Project > Rate My Resident' 카테고리의 다른 글
5. Query Callback (쿼리콜백) in Node.js (0) | 2023.04.11 |
---|---|
3. Spread Operator (Managing Array State) (0) | 2023.03.02 |
2. Connect Node.js to React.js with Express and Mysql (0) | 2023.01.02 |
1. How to put props to a page with enter key (엔터키 눌렀을 때 페이지로 인자 넘겨주기) (0) | 2022.12.31 |
0. Motivation / Folder Structure (0) | 2022.12.24 |