D
D
DeniSidorenko2020-12-07 12:02:17
JavaScript
DeniSidorenko, 2020-12-07 12:02:17

React/Redux on page throws undefined added array to object?

Hello, I have the following code

export function fetchCategories() {
  return async dispatch => {
    dispatch(fetchCategoriesStart())
    try {
      const response = await axios.get('/api/category/categories')
      const categories = []
      categories.push(response.data.data)
      categories[0].forEach((category) => {
        axios.get('/api/product/findById/'+ category._id)
          .then(response => category.allProducts = response.data.products)

      })
      console.log(categories)
      dispatch(fetchCategoriesSuccess(categories))
    } catch (e) {
      dispatch(fetchCategoriesError(e))
    }
  }
}


When getting a category, I make a query by category ID and get an array of products, which I add as an array to the Category object. However, when I access the state in the component, there is no allProducts. I can't figure out what's the reason

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-12-07
@Casufi

This line is synchronous

const response = await axios.get('/api/category/categories')

This one is no
axios.get('/api/product/findById/'+ category._id)
          .then(response => category.allProducts = response.data.products)

And you dispatch while the asynchronous code has not been executed. Have you read the editorial documentation? Are you familiar with the concept of immutability, and in what place is it applied to the store?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question