Wanhenri / Projeto-ERP

0 stars 0 forks source link

ERROR Fetch in Data #26

Closed Wanhenri closed 4 years ago

Wanhenri commented 4 years ago
export default function Data () {
    const [product, setproduct] = useState([]);
    useEffect(() => {
      fetch(`${process.env.REACT_APP_API_URL}/product_item`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json"
        }
      })
        .then(response => response.json())
        .catch(error => console.log(error));

    }, []);

      useEffect(() => {
      console.log(product)
    },[product])

  return (    
      <Wrapper >
        {product.map((products) => <h1 key={products.id}>{products.id}</h1>)}
        <SimpleTable name="Product" code="Code" price="Price" button="Add Product" path="/product"/>
        <SimpleTable name="Vendor"  code="CNPJ" price="City " button="Add Vendor" path="/vendor"/>
      </Wrapper>    
  );
}

TypeError: Object of type Product is not JSON serializable

Wanhenri commented 4 years ago

To solve this problem, configure a route output as a json file:

def get_user(self):
    product = Product.query.all()
    results = [ 
        {
            "id":products.id,
            "name":products.name,
            "code":products.code,
            "price":products.price
        } for products in product]

    return {"count": len(results), "product": results}

similar feat for the vendor

Wanhenri commented 4 years ago

I can read via the console in the browser, but fetch does not pass to useState

export default function Data () {
    const [product, setProduct] = React.useState([]);
    useEffect(() => {
      fetch(`${process.env.REACT_APP_API_URL}/product_item`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json"
        }
      })
        .then((response) => response.json())
        .then(data => {
          setProduct(data)
        })
        .catch((error) => console.log(error));

    }, []);

    useEffect(() => {
      console.log(product)
    },[product])

    return (    
        <Wrapper >
          <h1>TESTE</h1>
          {product.map(w => (
            <h1>{w.name}</h1>
           ))}
          <SimpleTable name="Product" code="Code" price="Price" button="Add Product" path="/product"/>
          <SimpleTable name="Vendor"  code="CNPJ" price="City " button="Add Vendor" path="/vendor"/>
        </Wrapper>    
    );
Wanhenri commented 4 years ago

Solution:

Wanhenri commented 4 years ago
Wanhenri commented 4 years ago

Use:

Wanhenri commented 4 years ago

or I will create other:

const [state, setState] = React.useState([]);

and pass the

setState(data.count)