Home > Back-end >  Load Data from Json file
Load Data from Json file

Time:12-03

Please Help me in this code I am UI designer and have not idea with code I have Json file have data Start with id 1 to id 25, I load this data using id and math.random() the code work but my problem the same id show twice or more than twice i just need to show the 25 ids unique for example the result is (2, 4, 18, 14, 7, 13, 13, 4) but i don't want same id show more than one and when the 25 ids show them all stop the function

the back-end code of json file

const express = require('express');
const app = express();
const importData = require("./data.json");
const port = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.get('/posts', (req, res) => {
    res.send(importData);
});

app.get('/posts/:id', (req, res) => {
  const post = importData.find(c => c.id === parseInt(req.params.id));
  if (!post) res.status(404).send("Error");
  res.send(post);
});

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Credentials", true);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
  next();
});


app.listen(port, () => {
  console.log(`Example app listening at ${port}`);
});

front-end js file

const container = document.getElementById('container'); const loading = document.querySelector('.loading');

// this load 4 posts
getPost();
getPost();
getPost();
getPost();

window.addEventListener('scroll', () => {
    const { scrollTop, scrollHeight, clientHeight } = document.documentElement;

    console.log( { scrollTop, scrollHeight, clientHeight });
    
    if(clientHeight   scrollTop >= scrollHeight - 5) {
        // show the loading animation
        showLoading();
    }
});

function showLoading() {
    loading.classList.add('show');
    
    // load more data
    setTimeout(getPost, 300)
}

async function getPost() {
    // the orginal url have (25) id in the json file
    // tips this is fake url i can't post the orginal url because it will my server
    const postResponse = await fetch(`https://example.com/posts/${getRandomNr()}`);
    const postData = await postResponse.json();
    
    const data = { post: postData};
    
    addDataToDOM(data);

    console.log(data);
}

function getRandomNr() {
    return Math.floor(Math.random() * 25)   1;
}

function addDataToDOM(data) {
    const postElement = document.createElement('div');
    postElement.classList.add('blog-post');
    postElement.innerHTML = `
        <h2 >${data.post.title}</h2>
        <p >${data.post.body}</p>
        <div >
            <img src="${data.post.src}" alt="${data.post.title}" />
            <span>${data.post.title}</span>
        </div>
    `;
    container.appendChild(postElement);
    
    loading.classList.remove('show');
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div  id="container">
        <h1>Blog Posts</h1>
    <!--    <div >
            <h2 >Blog post title</h2>
            <p >Lorem ipsum dolor, sit amet consectetur adipisicing elit. Provident quod debitis in repellat veritatis minus ab ex maiores itaque quis.</p>
            <div >
                <img src="https://randomuser.me/api/portraits/women/26.jpg" alt="pic" />
                <span>Leah Taylor</span>
            </div>
        </div> -->
    </div>
    
    <div >
        <div ></div>
        <div ></div>
        <div ></div>
    </div>    
    <script src="script.js"></script>
</body>
</html>

CodePudding user response:

You can use a function and an array to handle not repeat same number like below. You can put numbers array to top of the implementation.

This is not smart way to do that. You are saying you are UI Designer. So, I implemented understandable way rather than smarter way.


var numbers = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 18, 20, 21, 22,
  23, 24, 25,
];

function getRandomNr() {
  var x = Math.floor(Math.random() * numbers.length);
  const temp = numbers[x];

  // find index of random value in numbers
  // and delete it to not repeat number again
  var index = numbers.indexOf(temp);
  if (index > -1) {
    numbers.splice(index, 1);
    return temp;
  } else {
    // if code goes here that means
    // we got all 25 numbers between 1 and 25
    // and the numbers array is empty
    // so we can return -1 or anything we want
    return -1;
  }
}

CodePudding user response:

Try something like var array = Object.values(myobject) this will save all the object's own enumerable property values in an array. Then you want to shuffle the array. You can do that with this code. var shuffledArray = array.sort((a, b) => 0.5 - Math.random()); In the end you will have an array with all the values of the object in random order.

CodePudding user response:

The solution to your problem is indeed by creating a list of items which is then iterated.

Besides the mentioned approach another way to do that is to generate four distinct numbers and than use your code to actually do something useful with them.

function showLoading() {
    loading.classList.add('show');
    const rnd = new Set();
    do {
        rnd.add(getRandomNr());
    } while (rnd.size < 4);
    // load more data
    setTimeout(()=>rnd.forEach(nr => getPost(nr), 300));
}
async function getPost(id) { 
    const postResponse = await fetch(`https://example.com/posts/${id}`);
......
}

Just for clarification: A set is a list of items, where each item can only exist once. So if there is already, in your case, a number that was added it won't be added again, leaving you with distinct items.

Full code should look something like this:

const container = document.getElementById('container');
const loading = document.querySelector('.loading');

window.addEventListener('scroll', () => {
  const {
    scrollTop,
    scrollHeight,
    clientHeight
  } = document.documentElement;

  console.log({
    scrollTop,
    scrollHeight,
    clientHeight
  });

  if (clientHeight   scrollTop >= scrollHeight - 5) {
    showLoading();
    // show the loading animation
  }
});

function showLoading() {
  loading.classList.add('show');
  const rnd = new Set();
  do {
    rnd.add(getRandomNr());
    console.log(88)
  } while (rnd.size < 4);
  // load more data
  console.log(rnd)
  setTimeout(() => rnd.forEach(nr => getPost(nr), 300));
}
async function getPost(id) {
  const postResponse = await fetch(`https://example.com/posts/${id}`);
  const postData = await postResponse.json();
  const data = {
    post: postData
  };

  addDataToDOM(data);
}

function getRandomNr() {
  return Math.floor(Math.random() * 25)   1;
}

function addDataToDOM(data) {
  const postElement = document.createElement('div');
  postElement.classList.add('blog-post');
  postElement.innerHTML = `
        <h2 >${data.post.title}</h2>
        <p >${data.post.body}</p>
        <div >
            <img src="${data.post.src}" alt="${data.post.title}" />
            <span>${data.post.title}</span>
        </div>
    `;
  container.appendChild(postElement);

  loading.classList.remove('show');
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container" id="container">
    <h1>Blog Posts</h1>
    <!--    <div >
            <h2 >Blog post title</h2>
            <p >Lorem ipsum dolor, sit amet consectetur adipisicing elit. Provident quod debitis in repellat veritatis minus ab ex maiores itaque quis.</p>
            <div >
                <img src="https://randomuser.me/api/portraits/women/26.jpg" alt="pic" />
                <span>Leah Taylor</span>
            </div>
        </div> -->
  </div>

  <div class="loading">
    <div class="ball"></div>
    <div class="ball"></div>
    <div class="ball"></div>
  </div>
  <script src="script.js"></script>
</body>

</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related