Making API Call with Hooks PART 2

 

1. Making API Call while using React Hooks

1.1 Avoiding Unnecessary API Calls

Leaderboard Component Code

File: src/components/Leaderboard/index.js

...
const Leaderboard = () => {
...
useEffect(() => {
const getLeaderboardData = async () => {
setApiResponse({... })
const response = await fetch(url, options)
...
}
getLeaderboardData()
})
...
}
export default Leaderboard
JSX
Collapse

In the above code, Effect execute multiple times, and many API Calls are made

The Effect should execute, and an API call should be made only once, so pass empty dependency array as a second argument to the

useEffect

File: src/components/Leaderboard/index.js

...
const Leaderboard = () => {
...
useEffect(() => {
const getLeaderboardData = async () => {
setApiResponse({... })
const response = await fetch(url, options)
...
}
getLeaderboardData()
}, [])
...
}
export default Leaderboard
JSX
Collapse

2 Updating Object in the State

Class Components

  • The Object provided to the 
    setState()
     will merge into the current state object
  • The newly created object contains all the keys and values

Function Components

  • The Object provided to the setter function will replace the current state object
  • The newly created object may not contain all the keys and values

While updating the state, use callback function and spread operator to get all the key values from the current state object

File: src/components/Leaderboard/index.js

...
const Leaderboard = () => {
const [apiResponse, setApiResponse] = useState({...})
useEffect(() => {
const getLeaderboardData = async () => {
...
const response = await fetch(url, options)
...
if (response.ok) {
setApiResponse((prevApiResponse) => ({
...prevApiResponse,
status: apiStatusConstants.success,
data: responseData
}))
}
}
getLeaderboardData()
}, [])
...
}
export default Leaderboard
JSX
Collapse

3. Leaderboard Application Code

Use the below command to get the Final Code for Leaderboard Application

ccbp start RHSIVA7S2I
SHELL

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form