0

I've got a problem with making a correct loop in React. I want to fetch data from JSON to don't repeat components. I tried to make two loops and then two maps, but everything was in bad order. The other problem is that "description" is also an array that's why I'm not able to deal with it

JSON:

{
  "oswiecim": [
    {
      "header": "Oświęcim Zasole",
      "description": [
        "Rejon ulic św Maksymiliana Kolbego",
        "i Stanisławy Leszczyńskiej"
      ]
    },
    {
      "header": "Oświęcim Zasole",
      "description": [
        "Rejon ulic Więźniów Oświęcimia",
        "Obozowej, Polnej i Legionów"
      ]
    },
    {
      "header": "Stare Miasto",
      "description": [
        "Rejon Rynku i Placu ks. Jana Skarbka oraz ",
        "ulic Zamkowej i Władysława Jagiełły"
      ]
    },
    {
      "header": "Stare Miasto",
      "description": [
        "Cmentarz Parafialny oraz rejon",
        "ul. Wysokie Brzegi."
      ]
    },
    {
      "header": "Osiedle Chemików",
      "description": [
        "Największa pod względem liczby ludności",
        "dzielnica Oświęcimia"
      ]
    }
  ]
}

React:

import '../../styles/selection/Selection.scss'
import { useEffect, useState } from 'react';

const Selection = () => {
    const [data, setData] = useState({})
    const getData = async () => {
        await fetch('https://jsoneditoronline.org/#left=cloud.b95a27020e1c45e9b3a7c95a74fc5d49', {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
            .then(res => res.json())
            .then(data => {
                setData(data)

            })
    }
    useEffect(() => {
        getData()
    }, [])

    const headers = []
    const descriptions = []
    for (const item of data.oswiecim) {
        headers.push(item.header)

        descriptions.push(item.description)

    }



    return (
            <div className="selection">
                    {headers.map(item => (
                        <h1>{item}</h1>
                    ))}
                  {descriptions.map(item => (
                    item.map(elem => (
                        <p>{elem}</p>
                    ))
                ))}
            </div>
    );
}

export default Selection;

The result should look like this:

example

2 Answers 2

1

You don't need to separate header and description in two different variables.

So try something like this:-

return (
    <div className="selection">
      {data.oswiecim?.map((item) => (
        <>
          <h1>{item.header}</h1>
          {item.description?.map((description) => (
            <p>{description}</p>
          ))}
        </>
      ))}
    </div>
  );

Live demo

Sign up to request clarification or add additional context in comments.

2 Comments

I really appreciate your response, it helped me a lot :) Can I ask you what's the reason for the question mark right here: {data.oswiecim?.map()}?
That stands for optional chaining. If your api does not return oswiecim in your data then by using this chaining you can prevent page break or error in future. You can find more info about optional chaing here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
1

Replace the setData(data); with following. It will just give the array you need to iterate,

setData(data.oswiecim);

Remove the following code,

const headers = []
    const descriptions = []
    for (const item of data.oswiecim) {
        headers.push(item.header)

        descriptions.push(item.description)

    }

Replace return statement with following,

<div className="selection">
    {data &&
        data.map(item => (
            <>
                <div>{item.header}</div>
                {item.description &&
                    item.description.map(descriptionItem => <p>{descriptionItem}</p>)}
            </>
        ))}
</div>

2 Comments

@Stairss, check this out!
thank you, this is exactly what I wanted :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.