In this next example we take a look how we interact with an API.
You will see that it works straight forward.
1. Start with the usual index.html-file where you define a div-Tag with an id of your choice.
<!-- index.html -->
<div id='myapp'></div>
<script type='module' src='app.js'></script>
2. In app.js, we set up our project as usual.
We create a state variable that will hold the data we are going to fetch.
// app.js
import { RobJSApp } from './Rob.js'
import { DisplayPlanets, fetchPlanets } from './DisplayPlanets.js'
const app = new RobJSApp('myapp')
app.init('app')
app.defineStateVar('planets', [])
app.registerComponent(DisplayPlanets, 'dp1', ['planets'])
app.DisplayPlanets = {}
app.DisplayPlanets.fetchPlanets = fetchPlanets
app.initialRender(DisplayPlanets, 'dp1')
3. Create a component called DisplayPlanets and the function called fetchPlanets that will make the API call and update the state.
The updated state will cause a re-render and the data will be displayed.
// DisplayPlanets.js
export const fetchPlanets = async () => {
try {
// Fetching planets from SWAPI and passing it into a state variable
const response = await fetch('https://swapi.dev/api/planets/')
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
const data = await response.json()
app.updateState('planets', data.results)
} catch (error) {
console.error('Error fetching planets:', error)
}
}
export const DisplayPlanets = (id) => {
const list = app.state.planets.map(planet => `<li>Name: ${planet.name}, Population: ${planet.population}, Terrain: ${planet.terrain}</li>`).join('')
return `
<div id=${id}>
<button onclick='app.DisplayPlanets.fetchPlanets()'>Get Planets</button>
${app.state.planets.length > 0 ? `<ul>${list}</ul>` : ''}
</div>
`
};
4. With a bit of styling it looks and works like this.
© - RobJS.org - All rights reserved