Загрузка данных


// store/slices/documentsSlice.ts - обновляем асинхронные thunks
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
import type { Document, DocumentData, Cell } from '../../types';
import { api } from '../../services/api';
import { RootState } from '../index';

// ВСПОМОГАТЕЛЬНАЯ ФУНКЦИЯ ДЛЯ ПОЛУЧЕНИЯ userId ИЗ STATE
const getUserId = (getState: () => unknown): string | null => {
    const state = getState() as RootState;
    return state.auth.user?.id || null;
};

// ОБНОВЛЁННЫЕ THUNKS С ПЕРЕДАЧЕЙ userId
export const fetchDocuments = createAsyncThunk(
    'documents/fetchAll',
    async (_, { getState }) => {
        const userId = getUserId(getState);
        return await api.getDocuments(userId || undefined);
    }
);

export const fetchDocumentById = createAsyncThunk(
    'documents/fetchById',
    async (id: string, { getState }) => {
        const userId = getUserId(getState);
        return await api.getDocument(id, userId || undefined);
    }
);

export const createDocument = createAsyncThunk(
    'documents/create',
    async ({ name, rows, cols }: { name: string; rows: number; cols: number }, { getState }) => {
        const userId = getUserId(getState);
        return await api.createDocument(name, rows, cols, userId || undefined);
    }
);

export const updateDocument = createAsyncThunk(
    'documents/update',
    async ({ id, data, rows, cols }: { id: string; data: Cell[][]; rows: number; cols: number }, { getState }) => {
        const userId = getUserId(getState);
        return await api.updateDocument(id, data, rows, cols, userId || undefined);
    }
);

export const renameDocument = createAsyncThunk(
    'documents/rename',
    async ({ id, newName }: { id: string; newName: string }, { getState }) => {
        const userId = getUserId(getState);
        return await api.renameDocument(id, newName, userId || undefined);
    }
);

export const deleteDocument = createAsyncThunk(
    'documents/delete',
    async (id: string, { getState }) => {
        const userId = getUserId(getState);
        await api.deleteDocument(id, userId || undefined);
        return id;
    }
);

export const duplicateDocument = createAsyncThunk(
    'documents/duplicate',
    async (id: string, { getState }) => {
        const userId = getUserId(getState);
        return await api.duplicateDocument(id, userId || undefined);
    }
);

// ОСТАЛЬНОЙ КОД БЕЗ ИЗМЕНЕНИЙ...