0

I have a function consumed from a service where it returns a promise object when called, on fulfillment I need to extract a value.

 const isAdmin = some.service.isUserAuthorized({
        group: "group_id",
    }).then((response) => response.isAuthorized)
        .then((value) => {
            return value;
        });
const initialState = {user:"some_name",isAnAdmin:isAdmin }

// it provides promise object as the result, but i need the value of the promise object once completed

export const userDetailsSlice = createSlice({
  name: 'userDetails',
  initialState ,
  reducers: {
  },
})

export default userDetailsSlice.reducer
milas86534
  • 39
  • 4

1 Answers1

0

You can use createAsyncThunk for your async method and read the resulting value using an extraReducer in your slice. Have a look at this answer:

const checkUserIsAuthorized = createAsyncThunk(
  'users/isAuthorized',
  async (userId, thunkAPI) => {
    const { isAuthorized } = await some.service.isUserAuthorized({
        group: "group_id",
    })
    return isAuthorized
  }
)

export const userDetailsSlice = createSlice({
  name: 'userDetails',
  initialState ,
  extraReducers: (builder) => {
    // Add reducers for additional action types here, and handle loading state as needed
    builder.addCase(checkUserIsAuthorized.fulfilled, (state, action) => {
      // Add value to the state array
      state.isAnAdmin.push(action.payload)
    })
  },
})
Janik
  • 688
  • 1
  • 6
  • 12