How to get a category from a product using the useEffect hook?

  • 0
    I can't understand why I can't get the category by catId from the product.
    That is, first I create useState separately for product and category.
    Then, using axios and useEffect, I get the product through my API via slug (the product is all okay, everything is cool).
    Next, I also want to get the category and I need to pass the catId parameter, and it does not work from the previously received product.

    Below is the code:
    import logo from './logo.svg'
    import './App.css'
    
    import React, {useState, useEffect} from 'react'
    import axios from 'axios'
    
    const App = () => {
    
      const [product, setProduct] = useState({})
      const [category, setCategory] = useState({})
    
      useEffect(() => {
        const fetchProduct = async () => {
          const {data} = await axios.get('/api/products/random-lucky-box')
    
          setProduct(data)
        }
    
        fetchProduct()
      }, [])
    
      useEffect(() => {
        const fetchCategory = async () => {
          const {data} = await axios.get(`/api/categories/${product.catId}`)
    
          setCategory(data)
        }
    
        fetchCategory()
      }, [])
    
      return (
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <p>
              Название: {product.name} <br />
              Цена: {product.price}
            </p>
    
          </header>
        </div>
      )
    }
    
    export default App


    P.S. The API has separately tested everything works, for example, if you pass a static id parameter.
    React Anonymous, Nov 8, 2019

  • 1 Answers
  • 0
    useEffect(() => {
    axios.get('/api/products/random-lucky-box').then(r => setProduct(r.data));
    }, []);

    useEffect(() => {
    if (product.catId) {
    axios.get(`/api/categories/${product.catId}`).then(r => setCategory(r.data));
    }
    }, [ product ]);
    Adalaide McFarland

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!