Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to shuffle nested array with useState

I’m making a Quiz app in react native and I want to shuffle the order of questions each time someone picks the quiz. I was thinking about using shuffle from lodash but I’m not totally sure how to do for nested array.

const getTest = async () => {

     try {
        const response = await fetch('https://tgryl.pl/quiz/test/'.concat(route.params.testId));
        const json = await response.json();
        setData(json);
     }
     catch (error) {
          console.error(error);
     } 
}

I was thinking about something like setData(_.shuffle(data.tasks)) ?? I have no idea

The JSON looks like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

Apparently the array to be shuffled is stored in the tasks property of the response object, so you should shuffle that array and assign it back to that property:

json.tasks = _.shuffle(json.tasks);
setData(json);

Even though this mutates an object and then passes it to setData (which presumably calls setState/useState, and such mutation is usually a code smell), this is not an issue here, as this object was never used before for the state.

Unrelated, but I would not call that variable json. It is a JavaScript object. JSON is the term for the text format that the json() method retrieves from the request and converts to the object/array.

Use a name that describes the content, like quiz.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading