ThunkMiddleware

Struct ThunkMiddleware 

Source
pub struct ThunkMiddleware;
Expand description

§Thunk middleware

Thunk middleware enables us to introduce side-effects in a redux application.

With this middleware you can dispatch actions and thunks to your store.

§Fn example

use async_trait::async_trait;
use std::sync::Arc;
use std::time::Duration;
use redux_rs::{Store, StoreApi};
use redux_rs::middlewares::thunk::{ActionOrThunk, ThunkMiddleware, Thunk};
use tokio::time::sleep;

#[derive(Default, Debug, PartialEq)]
struct UserState {
    users: Vec<User>,
}

#[derive(Clone, Debug, PartialEq)]
struct User {
    id: u8,
    name: String,
}

enum UserAction {
    UsersLoaded { users: Vec<User> },
}

fn user_reducer(state: UserState, action: UserAction) -> UserState {
    match action {
        UserAction::UsersLoaded { users } => UserState { users },
    }
}

async fn load_users(store_api: Arc<impl StoreApi<UserState, UserAction>>) {
    // Emulate api call by delaying for 100 ms
    sleep(Duration::from_millis(100)).await;

    // Return the data to the store
    store_api
        .dispatch(UserAction::UsersLoaded {
            users: vec![
                User {
                    id: 0,
                    name: "John Doe".to_string(),
                },
                User {
                    id: 1,
                    name: "Jane Doe".to_string(),
                },
            ],
        })
        .await;
}
let store = Store::new(user_reducer).wrap(ThunkMiddleware).await;
store.dispatch(ActionOrThunk::Thunk(Box::new(load_users))).await;

let users = store.select(|state: &UserState| state.users.clone()).await;
assert_eq!(users, vec![]);

sleep(Duration::from_millis(200)).await;

let users = store.select(|state: &UserState| state.users.clone()).await;
assert_eq!(
    users,
    vec![
        User {
            id: 0,
            name: "John Doe".to_string(),
        },
        User {
            id: 1,
            name: "Jane Doe".to_string(),
        },
    ]
);

§Trait example

use async_trait::async_trait;
use std::sync::Arc;
use std::time::Duration;
use redux_rs::{Store, StoreApi};
use redux_rs::middlewares::thunk::{ActionOrThunk, ThunkMiddleware, Thunk};
use tokio::time::sleep;

#[derive(Default, Debug, PartialEq)]
struct UserState {
    users: Vec<User>,
}

#[derive(Clone, Debug, PartialEq)]
struct User {
    id: u8,
    name: String,
}

enum UserAction {
    UsersLoaded { users: Vec<User> },
}

fn user_reducer(state: UserState, action: UserAction) -> UserState {
    match action {
        UserAction::UsersLoaded { users } => UserState { users },
    }
}

struct LoadUsersThunk;
#[async_trait]
impl<Api> Thunk<UserState, UserAction, Api> for LoadUsersThunk
    where
        Api: StoreApi<UserState, UserAction> + Send + Sync + 'static,
{
    async fn execute(&self, store_api: Arc<Api>) {
        // Emulate api call by delaying for 100 ms
        sleep(Duration::from_millis(100)).await;

        // Return the data to the store
        store_api
            .dispatch(UserAction::UsersLoaded {
                users: vec![
                    User {
                        id: 0,
                        name: "John Doe".to_string(),
                    },
                    User {
                        id: 1,
                        name: "Jane Doe".to_string(),
                    },
                ],
            })
            .await;
    }
}
let store = Store::new(user_reducer).wrap(ThunkMiddleware).await;
store.dispatch(ActionOrThunk::Thunk(Box::new(LoadUsersThunk))).await;

let users = store.select(|state: &UserState| state.users.clone()).await;
assert_eq!(users, vec![]);

sleep(Duration::from_millis(200)).await;

let users = store.select(|state: &UserState| state.users.clone()).await;
assert_eq!(
    users,
    vec![
        User {
            id: 0,
            name: "John Doe".to_string(),
        },
        User {
            id: 1,
            name: "Jane Doe".to_string(),
        },
    ]
);

Trait Implementations§

Source§

impl<State, Action, Inner> MiddleWare<State, ActionOrThunk<State, Action, Inner>, Inner, Action> for ThunkMiddleware
where Action: Send + 'static, State: Send + 'static, Inner: StoreApi<State, Action> + Send + Sync + 'static,

Source§

fn dispatch<'life0, 'life1, 'async_trait>( &'life0 self, action: ActionOrThunk<State, Action, Inner>, inner: &'life1 Arc<Inner>, ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

This method is called every time an action is dispatched to the store. Read more
Source§

fn init<'life0, 'life1, 'async_trait>( &'life0 mut self, inner: &'life1 Arc<Inner>, ) -> Pin<Box<dyn Future<Output = ()> + Send + 'async_trait>>
where Self: Send + 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

This method is called the moment the middleware is wrapped around an underlying store api. Initialization could be done here. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.