logo

Example: Talking to an API

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 { DisplayQuotes, fetchQuotes } from './DisplayQuotes.js'

const app = new RobJSApp('myapp')
app.init('app')

app.defineStateVar('quotes', [])
app.registerComponent(DisplayQuotes, 'dp1', ['quotes'])
app.DisplayQuotes = {}
app.DisplayQuotes.fetchQuotes = fetchQuotes

app.initialRender(DisplayQuotes, 'dp1')
    
    

3. Create a component called DisplayQuotes and the function called fetchQuotes that will make the API call and update the state.
The updated state will cause a re-render and the data will be displayed.

    
// DisplayQuotes.js

export const fetchQuotes = async () => {
    try {
        // Fetching quotes from Game of Thrones and passing it into a state variable
        const response = await fetch('https://api.gameofthronesquotes.xyz/v1/random/10')
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`)
        }
        const data = await response.json()
        app.updateState('quotes', data.results)
    } catch (error) {
        console.error('Error fetching quotes:', error)
    } 
}

export const DisplayQuotes = (id) => {

    const list = app.state.quotes.map(quote => `<li>${quote.character.name}: "${quote.sentence}"</li>`).join('')

    return `
        <div id=${id}>
            <button onclick='app.DisplayQuotes.fetchQuotes()'>Get Quotes</button>
            ${app.state.quotes.length > 0 ? `<ul>${list}</ul>` : ''}
        </div>
    `
};
    
    

4. With a bit of styling it looks and works like this.

© - RobJS.org - All rights reserved