Don't know how to properly access fetching result in redux state with hooks

Viewed 64

I'm trying to fetch data from my backend to my redux store to than access it in my functional React Component. (Using hooks instead of classes)

When I'm trying to fetch the data in the component itself like this:

useEffect(() => {
  const fetchCategories = async () => {
    const res = await trees.get('/categories')
    setCategories(res.data)
  }

  fetchCategories()
}, [])

it works and i have access to the data, but it's obviously not in the redux store, just in my components state. (I have my axios.create in a seperate file, so I can just fetch with tree.get)

And fetching in my action creator works aswell, I can successfully dispatch the responses data into my redux store like this:

export const fetchCategories = async () => {
  const res = await trees.get('/categories')
  dispatch({ type: FETCH_CATEGORIES, payload: res.data })
}

state in my redux store

But I don't know how to properly run my action creator to than access the data in the redux store from my React Component. I tried several things like:

const [categories, setCategories] = useState([{
    "value": "loading...",
    "icon": "music"
  }])

  useEffect(() => {
    const plsWork = async () => {
      const res = await fetchCategories()
      console.log(res)
    }

    plsWork()
  }, [])

or the useSelector Hook from redux, but I couldn't figure out a way, that's working. :(

2 Answers

You have to pass dispatch too as you can use useDispatch hook only in functional component. So for this:

export const fetchCategories = async ()=> (dispatch)=> {
  const res = await trees.get('/categories')
  dispatch({ type: FETCH_CATEGORIES, payload: res.data })
}

Then in component where you want to access the state you should use useSelector hook

const dispatch=useDispatch(); 

const categories=useSelector((state)=>state.reducerName.categories); // if you have more than one reducer write here reducername which you have assigned it in the combineReducer or if you are using only single reducer then you can also access it simply by state.categories

  useEffect(() => {
    
       dispatch(fetchCategories());
 

  
  }, [])

You used useDispach hook to update the redux store data and you should use useSelector hook to get the state data you want.

const categories = useSelector((state) => state.categories)
Related