Home > database >  How to get id from json with axios get request
How to get id from json with axios get request

Time:11-28

I'm trying to get idrestaurant for use as identifier from json document that has info like this on json objects on the database. Stuff is on PostgreSQL

This is a react website for a school project. I have tried printing response.data on a console log but nothing shows.

[{"idrestaurant":2,
"name":"Pizzeria Amigo",
"address":"Uusikatu 16",
"opening":"08:00",
"closing":"12:00",
"img":"testi.com/kuva.jpg",
"type":"fastfood",
"pricelvl":"3",
"owneruserid":1},
{"idrestaurant":3,
"name":"Burgers",
"address":"Katu 10",
"opening":"08:00",
"closing":"18:00",
"img":"testi.com/kuva.png",
"type":"fastfood",
"pricelvl":"1",
"owneruserid":1}]

I want to use id as idrestaurant as unique key for printing list of restaurant elements at Restaurant.js. Here is what I have been trying to do.

App.js

import React, { useEffect, useState } from 'react'
import './App.css'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import NavBar from './components/navBar'
import Restaurants from './components/Restaurants'
import searchRestaurant from './components/Search'
import Restaurant from './components/Restaurant'
import axios from 'axios'

const App = () => {
  const [restaurants, setRestaurants] = useState([])

  useEffect(() => {
    axios.get('http://MadeUpURL-app.herokuapp.com/restaurants')
      .then((response) => {
        setRestaurants(response.data)
      });
  }, []);
  return (
    <Router>
      <div>
        <NavBar />
        <Routes>
          <Route path='/restaurants' element={<Restaurants restaurants={restaurants} />} >
            <Route path="/restaurants/idrestaurant" element={<Restaurant restaurants={restaurants} />} />
          </Route>
          {/* <Route path='/Search' element={<Search />} /> */}
        </Routes>
      </div>
    </Router>
  );

}

export default App

Restaurants.js

import React from 'react'
import styles from './restaurants.module.css'
import Restaurant from './Restaurant'
import { Link } from 'react-router-dom'

const Restaurants = (props) => {
    return (
        <div className={styles.container}>
            <div className={styles.restaurantList}>
                {props.restaurants.map(restaurant => <Link to={restaurant.idrestaurant}>
                    <Restaurant key={restaurant.idrestaurant} />
                </Link>
                )}
            </div>
        </div>
    )
}

export default Restaurants

Restaurant.js

import React from 'react'
import styles from './restaurant.module.css'

export default function Restaurant(props) {
    return (
        <div className={styles.shop}>
            <div>
                <div><img src={props.img} className={styles.imageSize} /></div>
                <div>
                    <div className={styles.title}>{props.name}</div>
                    <div className={styles.type}>{props.type}</div>
                    <div className={styles.prange}>{props.pricelvl}</div>
                </div>
            </div>
        </div>
    )
}

CodePudding user response:

it is preferable to call api inside the Restaurants Component. Because setRestaurants will take time to update the state and in the mean time Restaurants Component will be render already so restaurants will be null in <Restaurants restaurants={restaurants} />

WORKING DEMO

Edit #SO-material-onclick-edit

Here is the code for App.js

import React, { useEffect, useState } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Restaurants from "./components/Restaurants";
import Restaurant from "./components/Restaurant";
    
const App = () => {
  return (
    <Router>
      <div>
        <Routes>
          <Route path="/" element={<Restaurants />} />
          <Route path="/restaurants" element={<Restaurants />}>
            <Route path="/restaurants/idrestaurant" element={<Restaurant />} />
          </Route>
          {/* <Route path='/Search' element={<Search />} /> */}
        </Routes>
      </div>
    </Router>
  );
};

export default App;

Here is the code for Restaurants.js

import React, { useEffect, useState } from "react";
import Restaurant from "./Restaurant";
import { Link } from "react-router-dom";
import axios from "axios";

const Restaurants = (props) => {
  const [restaurants, setRestaurants] = useState([]);

  const jsonFakeData = [
    {
      idrestaurant: 2,
      name: "Pizzeria Amigo",
      address: "Uusikatu 16",
      opening: "08:00",
      closing: "12:00",
      img: "testi.com/kuva.jpg",
      type: "fastfood",
      pricelvl: "3",
      owneruserid: 1
    },
    {
      idrestaurant: 3,
      name: "Burgers",
      address: "Katu 10",
      opening: "08:00",
      closing: "18:00",
      img: "testi.com/kuva.png",
      type: "fastfood",
      pricelvl: "1",
      owneruserid: 1
    }
  ];

  useEffect(() => {
    axios.get("https://jsonplaceholder.typicode.com/users").then((response) => {
      console.log(response.data);
      //setRestaurants(response.data);
      setRestaurants(jsonFakeData);
    });
  }, []);

  return (
    <div>
      <div>
        {restaurants && restaurants.length > 0
          ? restaurants.map((restaurant) => (
              <Link key={restaurant.idrestaurant} to={restaurant.idrestaurant}>
                <Restaurant
                  restaurant={restaurant}
                  key={restaurant.idrestaurant}
                />
              </Link>
            ))
          : ""}
      </div>
    </div>
  );
};

export default Restaurants;

Here is the code for Restaurant.js

import React from "react";

export default function Restaurant(props) {
  console.log(props, "prps");
  return (
    <div>
      <div>
        <div>
          <img src={props.restaurant.img} alt="img" />
        </div>
        <div>
          <div>{props.restaurant.name}</div>
          <div>{props.restaurant.type}</div>
          <div>{props.restaurant.pricelvl}</div>
        </div>
      </div>
    </div>
  );
}
  • Related