Home > Software engineering >  How to print JSON data from axios? -react-
How to print JSON data from axios? -react-

Time:10-27

The problem is I don't know how to print Json data with React.

JSON :

{
    "themes": [
        {
            "id": 1,
            "name": "nature",
            "trips": [
                {
                    "id": 1,
                    "location": "Jeju",
                    "price_discounted": 11200
                },
                {
                    "id": 2,
                    "location": "Seoul",
                    "price_discounted": 11200
                },
            ]
        }
    ]
}

and I tried

function Card() {
  const [users, setUsers] = useState([]);
  const fetchUsers = async () => {
    const response = await axios.get(process.env.REACT_APP_PRODUCT_URL);
    setUsers(response.data.themes);
    console.log(response.data);
  };

  useEffect(() => {
    fetchUsers();
  }, []);
  return (
    <div>
      {users.map((user) => (
        <li>{user.name.trips}</li>
      ))}
    </div>
  );
}

but I can`t get "trips"'s data.. Help me!

I can only get "themes"'s "id" and "name"

CodePudding user response:

You wrote user.name.trips which is not valid. Here, trips is not a child of name. To get a trip, you need to write:

user.trips[0].id or user.trips[1].price_discounted or ...

The index in bracket is needed because trips is an array here. Also, every trip is an object, so you need to specify which "key/value" pair you want to output.
The General code is:
user.trips[(index of trip)].(id or location orprice_discounted)

CodePudding user response:

In your json you are using variable wrongly. name is a string. trips is object. both are different props.

  {users.map((user) => {
    return user.trips(trip=>{
          return <li>{trip.location}</li>
          }

   }
 )}
  • Related