1

I have an app which fetch data from a JSON file. The problem is, it fetches the data from top to bottom. I want it to fetches randomly within the JSON file. How would I achieve this?

This is how I fetch the JSON:

componentDidMount() {
    const url = ''
    this.setState({ isLoading: true });  
    fetch(url)
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        dataSource: responseJson.product,
        dataBackup: responseJson.product,
        isLoading: false
      });
      })
    .catch((error) => {
      console.log(error)
    })
  }
quachhengtony
  • 125
  • 4
  • 17

1 Answers1

1

When you're reading a file there is no way to change the order of content. However, once the json is parsed, since your product key is an array, you can shuffle this array when you setting the state.

You can use the shuffle function from this answer How to randomize (shuffle) a JavaScript array?

Alternatively if you're using lodash, there is shuffle function for collections : https://lodash.com/docs/4.17.14#shuffle

Your final code would be:

// import shuffle function from linked anwser,
// or with lodash :
import { shuffle } from "lodash";

// ...

componentDidMount() {
  const url = "";
  this.setState({ isLoading: true });
  fetch(url)
    .then(response => response.json())
    .then(responseJson => {
      this.setState({
        dataSource: shuffle(responseJson.product),
        dataBackup: responseJson.product,
        isLoading: false
      });
    })
    .catch(error => {
      console.log(error);
    });
}
colinux
  • 3,989
  • 2
  • 20
  • 19