M
M
maxzbsss2020-11-21 13:04:11
JavaScript
maxzbsss, 2020-11-21 13:04:11

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

I can't figure out why I can't get the category by catId from the product.
That is, first I create a useState separately for the product and category.
Then, with the help of axios and useEffect , I get the product via my slug via my API (the product is displayed okay, everything is cool).
Next, I also want to get the category and I need to pass the catId parameter, but it doesn’t work from the previously received product.

Below 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


PS API separately tested everything works, for example, if you pass a static id parameter.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-11-21
@maxzbsss

You are trying to get a category before the product is received. That is, your product.catId is undefined. You need to add the product as a dependency to the effect in which you get the category, inside the effect itself, check that the category identifier exists - and only in this case make a request:

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 ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question