Home > Software engineering >  How do I output the data received through Redux Thunk?
How do I output the data received through Redux Thunk?

Time:06-04

I'm currently mastering redux and haven't really figured out how to output the data you get from the server using thunk. I in useEffect do a thunk dispatch, get server data, but they don't output because they come after a couple of seconds, so in useState just an empty array, and in store the desired data

// retrieve data from the store

const servicesData = useAppSelector((state) => state.services.services);
const [services, setServices] = useState(servicesData);
// store

export const store = createStore(
  reducers,
  {},
  composeWithDevTools(applyMiddleware(thunk))
);

I understood that useState does not pick up data that comes after a couple of seconds, it turns out it is necessary to add data through setState, but then why thunk? is it necessary to use it at all when receiving any data? I'm completely confused

CodePudding user response:

Your problem is the useState call. Never put the result from a useSelector into a useState. It will be used as the "initial state" of the useState and never update that state when the value from useSelector updates - useState doesn't work like that. Just directly use the value from store.

const services = useAppSelector((state) => state.services.services);

CodePudding user response:

Redux Thunk is middleware that allows you to return functions, rather than just actions, within Redux. This allows for delayed actions, including working with promises.


One of the main use cases for this middleware is for handling actions that might not be synchronous, for example, using axios to send a GET request. Redux Thunk allows us to dispatch those actions asynchronously and resolve each promise that gets returned. ` import { configureStore } from '@reduxjs/toolkit' import rootReducer from './reducer' import { myCustomApiService } from './api'

const store = configureStore({
  reducer: rootReducer,
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware({
      thunk: {
        extraArgument: myCustomApiService
      }
    })
})

// later
function fetchUser(id) {
  // The `extraArgument` is the third arg for thunk functions
  return (dispatch, getState, api) => {
    // you can use api here
  }
} 
  • Related