Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading screen when fetching data via Redux

I want to start adding loading screens to my components when I'm fetching data from my API. I've made some research and tried my best, but my loading screen never disappears and I don't know why. I've tried to solve this for a while now hehe.

Action:

const setDoors = data => {
  return {
    type: 'SET_DOORS',
    payload: {
      setDoors: data
    }
  }
}

...

export const fetchDoors = () => async (dispatch, getState) => {
  try {
    dispatch({ type: 'FETCH_DOORS' })
    const doors = await axios.get(`${settings.hostname}/locks`).data
    dispatch(setDoors(doors))

Reducer:

const initialState = {
  isLoading: false
}

export const fetchDoors = (state = initialState, action) => {
  switch (action.type) {
    case 'FETCH_DOORS':
      return { ...state, isLoading: true }

    case 'FETCH_DOORS_SUCCESS':
      return { ...state, doors: action.payload.setDoors, isLoading: false }

In my component I only have this:

if (this.props.isLoading) return <div>laddar</div>

And when I log it I'm always getting true:

const mapStateToProps = state => {
  console.log(state.fetchDoors.isLoading) // Always true
  return {
    doors: state.fetchDoors.doors,
    isLoading: state.fetchDoors.isLoading,
    controllers: state.fetchDoors.controllers
  }
}

Console

enter image description here

like image 823
Martin Nordström Avatar asked Feb 11 '26 14:02

Martin Nordström


1 Answers

You have a tricky small error in that you are not awaiting what you think you are awaiting.

Compare your

const doors = await axios.get(`${settings.hostname}/locks`).data

to

const doors = (await axios.get(`${settings.hostname}/locks`)).data

In the first case you are actually awaiting some undefined property .data on the promise (not the awaited result) that gets returned from the axios call.

In the second case, which should work, you're awaiting the promise, and then you get the .data property of the awaited promise.

I reproduced the issue in the small snippet below. Notice how fast the first result pops up, even though the promise is supposed to resolve after 4 seconds.

const getDataPromise = () => new Promise(resolve => setTimeout(() => resolve({data: 42}), 4000));

(async function e() {
  const data = await getDataPromise().data;
  
  console.log("wrong:   await getDataPromise().data = ", data)

})();

(async function e() {
  const data = (await getDataPromise()).data;
  
  console.log("right:   (await getDataPromise()).data = ", data)

})();
like image 66
jonahe Avatar answered Feb 13 '26 09:02

jonahe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!