Home > other >  React store data in a variable from API
React store data in a variable from API

Time:03-16

I am trying to store some of my data in a const variable. Like I am getting FAQ section data from an API call. Like this one, I have my data in restaurant.faq and there can be multiple data so I map through it and it is working perfectly. Suppose Now I have two questions and two answers and I am getting it perfectly.

{restaurant.faq?.map((f) => (
        <ListGroup.Item key={f.id}>
            Question - <strong>{f.question}</strong>
            <br />
            Answer - <strong>{f.answer}</strong>                    
        </ListGroup.Item>
        
    ))}

But I want to pass the same question and answer from this restaurant.faq in a const variable Like this in rows [{question, answer}] section. How Can I do this?

const data = {
        title: "FAQ",
        rows: [
            {
                question: "Lorem ipsum dolor sit amet,",
                answer: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed tempor sem. Aenean vel turpis feugiat,
                  ultricies metus at, consequat velit. Curabitur est nibh, varius in tellus nec, mattis pulvinar metus.
                  In maximus cursus lorem, nec laoreet velit eleifend vel. Ut aliquet mauris tortor, sed egestas libero interdum vitae.
                  Fusce sed commodo purus, at tempus turpis.`,
            },
            {
                question: "Nunc maximus, magna at ultricies elementum",
                answer:
                    "Nunc maximus, magna at ultricies elementum, risus turpis vulputate quam, vitae convallis ex tortor sed dolor.",
            },
            
        ],
    };

Update how to do the same with this one?

{restaurant.menu?.map((men) => (
                                            <ListGroup.Item key={men.id}>
                                                
                                                <Image src={men.image} alt={men.name} style={{height:'250px', width:'1800px'}} fluid />
                                                
                                            </ListGroup.Item>
                                            
                                        ))}

 const images = [
        {
          original: 'https://picsum.photos/id/1018/1000/600/',
        },
        {
          original: 'https://picsum.photos/id/1015/1000/600/',
        },
        {
          original: 'https://picsum.photos/id/1019/1000/600/',
         
        },
      ];

CodePudding user response:

You can do like this

const data = {
  title: "FAQ",
  rows: restaurant.faq?.map(({ question, answer}) => (
    { question,
      answer
    })
  )
  • Related