CS 312 - Assessment04 - Solution
For question 1, the solution was that you should not self-close PRs. Someone else needs to review the code first.
For question 2,
- prioritizing features is the job for the product owner
- performing code reviews is a job for the whole dev team
- determining who is working on which backlog item is also the job of the dev team.
For question 3, you were asked to identify what in the following code caused an infinite loop, and how to overcome it.
function SearchResults({ query }) {
const [results, setResults] = useState([]);
const getResults = async () => {
const response = await fetch(`${server}/api/search?q=${query}`);
if (!response.ok) {
throw new Error(response.statusText);
}
const serverResults = await response.json();
setResults(serverResults);
};
getResults();
const resultItems = results.map((result) => <li key={result.id}>{result.text}</li>);
return (<ul>{resultItems}</ul>);
}
The problem is that getResults
ultimately calls setResults
, which updates the state and causes the component to re-render. The re-render called getResults
again, and... infinite loop.
The solution is to use a useEffect
hook, which takes the fetch out of the main render cycle. We can have the hook trigger based on changes to the query, so we only need to update the state when there is something new to do.
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
const getResults = async () => {
const response = await fetch(`${server}/api/search?q=${query}`);
if (!response.ok) {
throw new Error(response.statusText);
}
const serverResults = await response.json();
setResults(serverResults);
};
getResults();
}, []);
const resultItems = results.map((result) => <li key={result.id}>{result.text}</li>);
return (<ul>{resultItems}</ul>);
}
Last updated 03/25/2021