简体   繁体   中英

ReactJS fetch data depending on selection

I got this app that has categories and subcategories stored in MongoDB. What I want is whenever the user chooses a category at the dropdown menu, next to it there is another dropdown that has the subcategories, depending on the selection I want to show the subcategories that belong to the category selection.

For example, we got 2 car manufacturers: Ford and Fiat

If Ford is selected I want to load on the second dropdown the cars of that brand and if the other is chosen then load Fiats cars.

Now all these I need to be done by fetching data from the API and loading it to the client.

In my mind I see two possible solutions: one is to get everything and check where it belongs and create a new array that will ship the data to the dropdown depending on the selection. The second option is to fetch for each selection the data from the API and push it to the dropdown.

Both solutions feel that are out of my reach because I can't find a non-expensive function to do everything or I am too confused at the moment and the solution might be easy and I kinda feel lost.

Here is the code of my component:

import { useState } from 'react'
import MUI Components...

//DATA FETCHING
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { listCategories } from '../../../redux/categories/categoriesActions'
import { listSubcategoriesByCategory } from '../../../redux/subcategories/subcategoriesActions'

export default function NewProduct() {
  const dispatch = useDispatch()
  const categoriesList = useSelector((state) => state.categoriesList)
  const subcategoriesList = useSelector((state) => state.subcategoriesList)
  const { loading, error, categories } = categoriesList
  const { subcategories } = subcategoriesList

  useEffect(() => {
    dispatch(listSubcategoriesByCategory(values.category))
    dispatch(listCategories())
  }, [dispatch])

  const [values, setValues] = useState({
    category: ``,
    subcategory: ``,
    name: '',
  })
  
  const handleChange = (prop) => (event) => {
    setValues({ ...values, [prop]: event.target.value })
    // Somewhere here I should set the state of the subcategories dropdown menu
  }

  return (
    <>
     <div>
      <FormControl>
       <Grid>
        <TextField
         value={values.category}
         onChange={handleChange('category')}>
          {categories.map((category) => (
           <MenuItem key={category._id} value={category.name}>
            category.name}
           </MenuItem>
          ))}
         </TextField>
        </Grid>
        <Grid item xs={6}>
         <TextField
          value={values.subcategory}
          onChange={handleChange('subcategory')}>
           {subcategories.map((subcategory) => (
            <MenuItem key={subcategory._id} value={subcategory.name}>
             {subcategory.name}
            </MenuItem>
           ))}
          </TextField>
         </Grid>
      )}
    </>
  )
}

Any suggestion is so much needed and appreciated at the moment.

Thank you in advance!

have you tried useEffect with dependency array with the first dropdown? When category change you can fetch subcategories. I also do it on my own project but never used redux before.

useEffect(() => {
   //fetch
}, [category])

So thank you all for taking the time to respond and take a look at my issue. The answer was all along inside my code but as I said, working for too long makes your vision blurry I guess.

The solution was very simple.

Instead of fetching the subcategories when the component mounts I fetch the in the handleChange function like so:

  const handleChange = (prop) => (event) => {
    setValues({ ...values, [prop]: event.target.value })
    dispatch(listSubcategoriesByCategory(event.target.value))

We get the selected value anyway when selecting a category, we already have an api GET request that fetches subcategories by passing the category and that is what I am doing in the handle change. I choose a category, I pass the category to redux function and I fetch whatever subcategory belongs to the chosen category.

Again, sorry for bothering you and thanks for the replies <3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM