Passing non-serializable blobs to async thunk payload creators: best practices? #5040
-
Hello! I have an application that uses a Redux Toolkit slice with a This works well in practice, and, as far as I know, no non-serializable state ever makes it into the store's state. However, the non-serializable I know that the Redux style guide says that keeping non-serializable values out of "state or actions" is "essential", and generally I like to try to follow those rules when possible. Is there a good, simple, easy alternative here? I don't really need the blob to be part of the action; it just kind of makes its way there by default. I'm aware of For concreteness, my code looks something like this: export const apiSlice = createAppSlice({
name: "api",
initialState,
reducers: (create) => ({
postImage: create.asyncThunk(
async (args: {
slug: string;
blob: Blob;
}): Promise<{ id: string; slug: string }> => {
const { slug, blob } = args;
const response = await fetch(`/upload/${encodeURIComponent(slug)}`, {
method: "POST",
body: blob,
});
const { id } = await response.json();
return { id, slug };
},
{
fulfilled: (state, action) => {
const { id, slug } = action.payload;
state.uploadedImages[slug] = id;
},
}
),
}),
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Yeah, RTK's serializability middleware does already default to ignoring that action path specifically for this reason:
As you noted, it doesn't get serialized across to the devtools, so in a sense that's "broken"... but it's also not realistically likely that you needed to inspect the blob in the devtools anyway. Also, as much as we've always tried to keep actions serializable to enable the time travel debugging aspects, in practice few people make use of that. So, if you do end up passing non-serializable values as a thunk arg, it's not the end of the world, and we tweaked the serializability middleware to account for that. |
Beta Was this translation helpful? Give feedback.
Yeah, RTK's serializability middleware does already default to ignoring that action path specifically for this reason:
ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],
As you noted, it doesn't get serialized across to the devtools, so in a sense that's "broken"... but it's also not realistically likely that you needed to inspect the blob in the devtools anyway. Also, as much as we've always tried to keep actions serializable to enable the time travel debugging aspects, in practice few people make use of that. So, if you do end up passing non-serializable values as a thunk arg, it's not the end of the world, and we tweaked the serializability middleware to account for that.