score:0

Accepted answer

why not pass the id as the variable in your request?

//is user null or not initialized?
sendinforequest(user?.id);
sendsalesrequest(user?.id);

there's nothing wrong with sending something explicitly--especially in a asynchronous context (it is also easier to test).

i think the bigger issue is your state might not be what you expect (like null). in my experience it makes the most sense to keep things as simple an explicit as possible.

in response to the comment i have some trouble understanding what you're asking, but if i understand the logic you basically want to do:

 -> send request -> get id -> use id

fundamentally that can't be done up front without knowing the id. what you probably want is something like:

-> send request (wait)
  -> with data do {
        action1, action2, etc...
  }

there's not enough code to give you any real information beyond that. if the user id doesn't exist in your state you need to request and use it. in redux that usually looks something like

//and please forgive me, there are a lot of different ways to write this
...
const doafteruseridexists = (userid) => {
  dispatch(a)
  dispatch(b)
  ...
  dispatch(x)
}
dispatch( initialaction(doafteruseridexists) )

//--in the backend
export const initialaction = (callback) => {
   return dispatch => {
       //do some business logic
       ...
       const user = new user()//id is created
       if(callback) {
         callback(user)
       }

       dispatch({
         type: cascade_user_function,
         user: user,
       })
   }
}

it isn't that different from what you're doing, except it has a linear flow. promise.all() also isn't viable because it will run all your events at the same time (pointless, you need an id first).

this isn't a perfect solution, but it gives you an idea of how to control the flow of data. you could also investigate sagas or other patterns to make "thunks" work. alternatively you could flip it so that the "sub logic" like posting info and sales requests happens in the back-end if they're part of a transaction.

it isn't magic, you need to find a solution that works for you. i tend to lean on callbacks because they are a linear flow, but there are many different patterns. i find this one the easiest to read.


Related Query

More Query from same tag