Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
3.0 kB
1
Indexable
Never
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// ** Axios Imports
import axios from 'axios'

// ** Fetch Users
// export const fetchData = createAsyncThunk('appUsers/fetchData', async params => {
  
//  const response = await axios.get('/api/logged/account')

//  return response.data
  
// })

export const fetchData = createAsyncThunk('appUsers/fetchData', async (_, thunkAPI) => {
  try {
    // Extract user data from localStorage
    const userData = localStorage.getItem('userData');

    if (!userData) {
      throw new Error('User data is not present in localStorage');
    }

    // Extract user ID from user data
    const userId = JSON.parse(userData)._id;
    console.log("userId22:", userId);

    if (!userId) {
      throw new Error('User ID is missing in the user data');
    }

    const response = await axios.get('/api/logged/account', {
      headers: {
        'user-id': userId,  // Change 'user' to 'User-ID'
        // Add other headers if needed
      },
    });
    console.log("API Response:", response.data);


    return response.data;
  } catch (error) {
    // Handle errors appropriately
    console.error('Error fetching data:', error.message);
    throw error;
  }
});



// ** Add User
export const addUser = createAsyncThunk('appUsers/addUser', async (data, { getState, dispatch }) => {
  const response = await axios.post('/apps/users/add-user', {
    data
  })
  dispatch(fetchData(getState().user.params))

  return response.data
})


// ** Delete User
export const deleteUser = createAsyncThunk('appUsers/deleteUser', async (id, { getState, dispatch }) => {
   try {
     // Extract user data from localStorage
     const userData = localStorage.getItem('userData')

     if (!userData) {
       throw new Error('User data is not present in localStorage')
     }

     // Extract user ID from user data
     const userId = JSON.parse(userData)._id
     console.log('userId22:', userId)

     if (!userId) {
       throw new Error('User ID is missing in the user data')
     }

     const response = await axios.delete('/api/logged/account', {
       headers: {
         'user-id': userId,
         'row-id':id
       }
     })
     console.log('API Response:', response.data)
     dispatch(fetchData(getState().user.params))

     return response.data
   } catch (error) {
     // Handle errors appropriately
     console.error('Error fetching data:', error.message)
     throw error
   }
});

export const appUsersSlice = createSlice({
  name: 'appUsers',
  initialState: {
    data: [],
    total: 1,
    params: {},
    allData: []
  },
  reducers: {},
  extraReducers: builder => {
    builder.addCase(fetchData.fulfilled, (state, action) => {
      state.data = action.payload.users
      state.total = action.payload.total
      state.params = action.payload.params
      state.allData = action.payload.allData
    })
  }
})

export default appUsersSlice.reducer
Leave a Comment