-1

I'm sure this has been asked and answered, but maybe I'm not able to phrase it correctly to find the right results.

Say I have two redux middleware operations:

  • a call to create an asset entity in the backend, then update the state with the result
  • a call to upload the asset data (requires the ID created on the create)

If I want to compose these two middleware operations into a single one how should I go about it? I thought a thunk made sense but I don't seem to have a way to get the resulting ID back from the first dispatch without diffing the before/after state.

2
  • What are you trying to compose? What are you trying to accomplish? Are you uploading the asset data to a different place than where it was created? Maybe a minimal reproducible example is necessary to help readers better understand what you are asking. Commented May 29 at 3:53
  • I should have known better than to post without an example - wishful thinking on my part - I'll make one up... Commented May 29 at 13:31

1 Answer 1

0

What I found gave me the desired effect was porting my basic operations to RTK Query.

From a thunk, when RTK query actions are dispatched, they can be awaited and there result is returned. For example:

export const createAndNameThing = createAsyncThunk(
  'things/createAndName',
  async (name: string, { dispatch }) => {
    // Step 1: Create the thing
    const createResult = await dispatch(
      thingApi.endpoints.createThing.initiate(undefined)
    ).unwrap();

    // Step 2: Update the thing with the name
    const updateResult = await dispatch(
      thingApi.endpoints.updateThing.initiate({
        id: createResult.id,
        data: name
      })
    ).unwrap();

    return updateResult;
  }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.