Skip to content
  • Unlock Pro
  • Log in with GitHub
Solution
Submitted over 2 years ago

Use of API to generate random advice

Caroline•210
@Carolkiarie
A solution to the Advice generator app challenge
View live sitePreview (opens in new tab)View codeCode (opens in new tab)

Solution retrospective


This was such a fun project to work on. I however need to store data in local storage so that when a user generates advice. When they come back to the page they will take from where they left from rather than seeing the default #1 advice which I have put. Any advice on how to do it In a simpler manner will be appreciated. Thank you and happy coding

Code
Select a file

Please log in to post a comment

Log in with GitHub

Community feedback

  • Amal Karim ✅•1,290
    @amalkarim
    Posted over 2 years ago

    Hi again, Carol

    It's quite simple to store data in a local storage. In your sandbox.js file, add this code just before the catch block:

    localStorage.setItem('lastAdviceId', userid);
    localStorage.setItem('lastAdviceText', useradvice);
    

    It will store the current useradvice and userid variables which we could get later.

    Then, when the page is loaded, we need to retrieve those two variables (if available) and write it on the page. Add this code below:

    window.onload = function() {
      const advice= document.querySelector('.advise');
      const generateAdvice= document.querySelector('.advisegenerated');
    
      if (localStorage.getItem('lastAdviceId')) {
        generateAdvice.innerText= `"${localStorage.getItem('lastAdviceText')}"`
        advice.querySelector('span').innerText= `#${localStorage.getItem('lastAdviceId')}`;
      }
    }
    

    Please remember though, that localStorage will still store the data even after the browser is closed. You can read about it and its alternative storage in this w3schools article.

    Alternatively, we could run the function that get the advice from adviceslip.com and render them in the page at window.onload, thus you don't need to write "default #1 advice" from the start.

    Hope this helps. Happy fun coding!

    Marked as helpful
  • Fazza Razaq Amiarso•2,320
    @fazzaamiarso
    Posted over 2 years ago

    Hello Caroline! Great work!

    Here is my way on saving the data to local storage. I did a bit of refactor.

    const getAdvice = async (adviceId) => {
        const params = adviceId === undefined ? 'advice' : `advice/${adviceId}`
        const base= `https://api.adviceslip.com/${params}`;
        const response = await fetch (base);
        return response.json()
    }
    
    const getFromLocalStorage = () => {
        return localStorage.getItem("adviceId");
    }
    
    const saveToLocalStorage = (adviceId) => {
        return localStorage.setItem("adviceId", adviceId);
    }
    
    const updateAdvice = (slip) => {
        const advice= document.querySelector('.advise');
        const generateAdvice= document.querySelector('.advisegenerated')
        // output the id of advice on the dom
        const useradvice = slip.advice;
        const userid = slip.id;
        
        generateAdvice.innerText= `" ${useradvice}"`
        advice.querySelector('span').innerText= `#${userid}`;
    }
    
    // fetch when first loaded
    document.addEventListener("DOMContentLoaded", () => {
        const savedAdviceId = getFromLocalStorage();
        getAdvice(savedAdviceId).then(response => {
            updateAdvice(response.slip);
        })
    })
    
    // click event
    const icon = document.querySelector('.icon');
    icon.addEventListener('click',()=>{
        getAdvice().then((response)=>{
            updateAdvice(response.slip);
            // save here
            saveToLocalStorage(response.slip.id)
        })
    })
    

    I hope it helps! Let me know if there are any problems! Cheers!

Join our Discord community

Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!

Join our Discord
Frontend Mentor logo

Stay up to datewith new challenges, featured solutions, selected articles, and our latest news

Frontend Mentor

  • Unlock Pro
  • Contact us
  • FAQs
  • Become a partner

Explore

  • Learning paths
  • Challenges
  • Solutions
  • Articles

Community

  • Discord
  • Guidelines

For companies

  • Hire developers
  • Train developers
© Frontend Mentor 2019 - 2025
  • Terms
  • Cookie Policy
  • Privacy Policy
  • License

Oops! 😬

You need to be logged in before you can do that.

Log in with GitHub

Oops! 😬

You need to be logged in before you can do that.

Log in with GitHub

How does the accessibility report work?

When a solution is submitted, we use axe-core to run an automated audit of your code.

This picks out common accessibility issues like not using semantic HTML and not having proper heading hierarchies, among others.

This automated audit is fairly surface level, so we encourage to you review the project and code in more detail with accessibility best practices in mind.

How does the CSS report work?

When a solution is submitted, we use stylelint to run an automated check on the CSS code.

We've added some of our own linting rules based on recommended best practices. These rules are prefixed with frontend-mentor/ which you'll see at the top of each issue in the report.

The report will audit 1st-party linked stylesheets, and styles within <style> tags.

How does the HTML validation report work?

When a solution is submitted, we use html-validate to run an automated check on the HTML code.

The report picks out common HTML issues such as not using headings within section elements and incorrect nesting of elements, among others.

Note that the report can pick up “invalid” attributes, which some frameworks automatically add to the HTML. These attributes are crucial for how the frameworks function, although they’re technically not valid HTML. As such, some projects can show up with many HTML validation errors, which are benign and are a necessary part of the framework.

Oops! 😬

You need to be logged in before you can do that.

Log in with GitHub

Oops! 😬

You need to be logged in before you can do that.

Log in with GitHub