Using variable for initialState in Redux Toolkit

Hey there,

I’m building my first React-Redux project and running into an issue trying to import in a local data.js file variable called allContentTilesData into my contentTilesSlice.js file (posted below). When I hardcode in the object for the initialState property it works fine, but when I replace it with the imported variable that should be referencing the same object it just returns the variable name as a string.

I’m guessing this is some silly syntax error I’m missing, but any help would be greatly appreciated!

import { createSlice } from '@reduxjs/toolkit';
import allContentTilesData from '../../data';

export const contentTilesSlice = createSlice({
    name: 'contentTiles',
    initialState: {
        contentTiles: {
            allContentTilesData
        }
    },
    reducers: {
        addTile: (state, action) => {
            const { id } = action.payload;
            state.contentTiles[id] = action.payload;
        }
    }
});

export const { addTile } = contentTilesSlice.actions;
export const selectContentTiles = (state) => state.contentTiles.contentTiles;
export default contentTilesSlice.reducer;

In case anyone stumbles on this with the same issue, I was able to fix it by:

  • making const initialState and assigning that to the imported data variable WITHOUT wrapping it in {}
import { createSlice } from '@reduxjs/toolkit';
import { contentTilesData } from '../../contentTilesData';

const initialState = {
    contentTiles: contentTilesData,
    amount: contentTilesData.length,
    isLoading: false
}

export const contentPageSlice = createSlice({
    name: 'contentPage',
    initialState,
    reducers: {
        addTile: (state, action) => {
            const tileId = action.payload;
            state.contentTiles[tileId] = action.payload;
        }
    }
});

export const { addTile } = contentPageSlice.actions;
export default contentPageSlice.reducer;