DEV Community

Matt Ruiz
Matt Ruiz

Posted on • Edited on

How do I store my data in Redux?

Storing your data in one of many redux 'dump' slices.

Redux slices can be used to easily interact with your data through one of the following slice types:

  1. dump - this is where we store all retrieved documents;
  2. current X - this is where we store the current document the User is interacting with;
  3. builders - this is where we track common environment flags like filters/sorting/etc;
  4. changes - this is where we keep track of the changes made so that we can perform a partial transaction updates;

In this article, we will talk through the redux dump. It will be React Native focused but the concepts are extremely similar when using redux in your Next.js app.

For this article, I will assume:

  1. You've worked with Redux before and have a solid grasp of the basics;
  2. You have an existing React Native project setup using TypeScript;

Steps for creating the Redux store with src/store.ts.

To start, let's imagine that you've got the following store.ts file:

// Comment: The following code imports configure store from redux toolkit;
import {configureStore} from '@reduxjs/toolkit';

// Comment: The following code declares the reducer for our redux store using our redux slices (atm just *users*);
export const store = configureStore({
  reducer: {
    users,
  },
});

// Comment: The following code grants UI-logic the ability to update redux;
export const useAppDispatch = () => useDispatch<AppDispatch>();

// Comment: The following code grants UI-logic the ability to read from redux;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
Enter fullscreen mode Exit fullscreen mode

In the above code snippet, we're creating one Redux slice and calling it users. We're also creating two hooks call useAppDispatch and useAppSelector which will allow us to perform both read and write operations on our redux data.

Storing all retrieved documents in dump slice.

The dump is where we keep all of the retrieved documents for one collection of data. For example, if you retrieved all Users within 10km, you would store them inside of a .users slice.

This .users slice would be an object:

// Comment: The following code imports the Users type, helper functions from redux toolkit and react-redux
import {User} from '@/model/index';
import {createSlice, PayloadAction} from '@reduxjs/toolkit';
import {TypedUseSelectorHook, useSelector} from 'react-redux';

// Comment: Declares the type for UsersSlice which is an Object of key:value pairs with key being the `User.id` and value being the User
export type UsersSlice = {[id: string]: User;};

const initialState: InitialState = {};

export const users = createSlice({
  name: 'users',
  initialState,
  reducers: {
    add: (state, action: PayloadAction<User[]>) => {
      const users = action.payload;

      users.forEach(user => {
        state[user.email] = user;
      });
    },
    remove: (state, action: PayloadAction<string>) => {
      const id = action.payload;

      delete state[id];
    },
  },
});

// The following export will be used the UI-logic via; `dispatch(UsersActions.add([...]);`
export const UsersActions = users.actions;

// The following default export will be used by the reducer/store.ts;
export default users.reducer;

Enter fullscreen mode Exit fullscreen mode

Using the new users slice;

When first loading an app, we sometimes load multiple Users based on the UX.

Imagine an initial app load for a Social Media App. On app load, we might load the 10 most recent Posts and the Users to created them.

We store all of these Users inside of the users slice. We also store all of the Posts we've retrieved (i.e., the 10 most recent) inside of the posts slice.

Benefits of storing your data inside of a dump

Easy access Related Documents

Let's imagine we have the following Post type:

type Post = {
 id: string;
 createdDate: number;
 /**
 * The user prop is set using User.id value of the User that created the Post
 */
 user: string;
};
Enter fullscreen mode Exit fullscreen mode

We're looking at a Post in the UI and on this Post there is a section that has some User information such as their Name and Profile Photo.

An image of a mobile app User who has their name, profile image, and their rating out of 5 stars. It is meant to display the intended UI - picture on the left and the name on the right overtop of the 5 star rating.

Here's how we would show this information:


type Props = {
  post: Post;
};

const PostComponent = (props: Props) => {
  const {post} = props;

  const users = useAppSelector(state => state.users);

  const userForPost = useMemo(() => users[post.user], [user, post.user]);

  return (
    <View style={styles.container}>
     <Image src={userForPost.image} style={styles.image} />
     <View>
       <Text style={styles.name}>{userForPost.name}</Text>
       <Ratings rating={5} />
     </View>
    </View>
  );
};
Enter fullscreen mode Exit fullscreen mode

As needed, developers can use the id of the selected User to retrieve the entirety of the User document.

This type of redux state management makes is easy and extremely consistent across data types.

We have dumps for all different type of data.

  • Matt

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay