Home > Mobile >  How to add an array as initial data in redux with its createEntityAdapter() method
How to add an array as initial data in redux with its createEntityAdapter() method

Time:11-15

just wanna add an array as initial data which gives me the ability to show some default data .

eventSlice.ts 

import {
  createEntityAdapter,
  createSlice,
  EntityAdapter,
} from "@reduxjs/toolkit";
import { RootState } from "../store";

export type EventType = {
  id: string;
  title: string;
  description: string;
  location: string;
  date: string;
  image: string;
  isFeatured: boolean;
};

const eventAdapter: EntityAdapter<EventType> = createEntityAdapter<EventType>({
  // sortComparer: (a: any, b: any) => b.date.localCompare(a.date),
});

const initialState = eventAdapter.getInitialState({
  status: "idle",
  error: null,
});

export const eventSlice = createSlice({
  name: "event",
  initialState,
  reducers: {
    eventLoading(state, action) {
      if (state.status === "idle") {
        state.status = "pending";
      }
    },
    eventCleaded: eventAdapter.removeAll,
    eventAdded: eventAdapter.addOne,
    eventUpdated: eventAdapter.updateOne,
  },
});

export const eventSelector = eventAdapter.getSelectors<RootState>(
  (state) => state.events
);
export const { eventAdded, eventCleaded, eventLoading, eventUpdated } =
  eventSlice.actions;

export default eventSlice.reducer;

and wanna before any access to the sliceEvent.ts by other other methods add some data : and for addition getAllEvents() is just array with some data which I want to add them to this flow

import { getAllEvents } from "../../../dummy-data";
import { useAppDispatch } from "../hooks";
import { eventAdded, EventType } from "./eventSlice";

export function CreateEvents() {
  const dispatch = useAppDispatch();
  const events: EventType[] = getAllEvents();
  const createEvents = events.map((event) =>
    dispatch(
      eventAdded({
        id: event.id,
        date: event.date,
        description: event.description,
        image: event.image,
        isFeatured: event.isFeatured,
        location: event.location,
        title: event.title,
      })
    )
  );
}

...............................

CodePudding user response:

If you really have that data available synchronously as your code above suggests, just add it from the beginning.


const initialState = eventAdapter.addMany(
  eventAdapter.getInitialState({
    status: "idle",
    error: null,
  }),
  [
    // your initial items go here
  ]
);

Doing so in a component render as you do above would lead to an infinite render cycle.

If you don't have the data available synchronously, initialize your state with state: uninitialized or something similar, fetch the data in a useEffect and dispatch it, while displaying a loading screen or something. You cannot "pause" React rendering to wait for something async, but you can always just display a loading spinner etc.

  • Related