Home > Software engineering >  How to get prevState value or all object in useState in React?
How to get prevState value or all object in useState in React?

Time:07-16

In trek_tours i have an array and inside array i have define object and inside object their are some array and the format is in below

treks_tours[  
{
title: "Everest Base Camp",
Prices: [
      "Price Start from 300 per/person",
      "Note - if you are number of people then we can make you good discount!",
],
},{
title: "Jungle Safare & Knowing Villager Life Style",
Prices: [
      "Price Start from 1650 per/person",
      "Note - if you are number of people then we can make you good discount!",
    ],
}
]

In this section i want to see the title and price name of differrent objects but i got repeted title same time. anyone please help me!!!

const [tripPrice, setTripPrice] = useState({});
const price = () => {
    treks_tours.map((price) =>
      setTripPrice((prevState) => ({
        ...prevState,
        price: price.Prices[0].split(" ")[3],
        title: price.title,
      }))
    );
  };
 console.log(tripPrice);
  useEffect(() => {
    price();
  }, []);

Output

CodePudding user response:

So from that array of objects, you want to individually console.log() all of them?

If so you want to individually console.log() all the objects all you have to do is:

trek_tours.forEach((tour) => {
  console.log(tour);
})

And then it will console.log() every object in array. Is that what you mean?

CodePudding user response:

If all you want to do is setTripPrice to array trek_tours then all to do is to say setTripPrice(trek_tours) - no need of anything else.

Then if you console.log(tripPrice) you get all the objects inside the array. If this is not what you mean please provide a codesandbox link

  • Related