1

I have 2 useEffect hooks for fetching all cars, then user can select some options, and component will rerendered with new fetched data, considering selected options, further user can navigate to some component and after that go back and all data will be fetched with initial state (all selected options will be erased). How to save selected options and use it for next renderings ? Furthermore It would be better to use only one hook, but i was confused in logic.

 useEffect(() => {
        fetchManufacturers().then(data => car.setManufacturers(data))
        fetchCarNames().then(data => car.setCarNames(data))

        fetchCars( null, null,  1, car.limit).then(data => {
            car.setCars(data.rows)
            car.setTotalCount(data.count)
        })
    },[car, car.page, car.selectedManufacturer, car.selectedCarName])


    useEffect(() => {
        fetchCars(car.selectedManufacturer.id , car.selectedCarName.id, car.page, car.limit).then(data => {
            car.setCars(data.rows)
            car.setTotalCount(data.count)
        })
    }, [car.page, car.selectedManufacturer, car.selectedCarName])

I tried to use getters and setters, but it save the 1 step back selected option.

  • 1. You could store the fetchedCars somewhere higher in the component tree that is always rendered 2. You could cache these API calls so next time they are near instance. – nlta Feb 01 '22 at 01:31

2 Answers2

0

You could either store your data in a parent component, but I suggest storing it in a context. Since it is related to a user decision, it could be interesting to get these data from wherever you want.

You can find a simple example on how to use a the React contextApi in my answer to another post.

There is other state management, but I like this one for its simplicity.

Quentin Grisel
  • 4,794
  • 1
  • 10
  • 15
0

React Redux is great for what you're trying to do. You can fetch all the raw car data once and save it in Redux. Every component can then fetch that data as needed. You can even store your user's car selections in Redux if you need to share that state between components.

K Mehta
  • 10,323
  • 4
  • 46
  • 76