Writing messages from response in redux store

24 Views Asked by At

I want to show toasts with messages that are sent from my backend. They are sent via "message" in the body of the response with the following type:

type Message = {
    text: string
    type: 'success' | 'error' | 'info' | 'warning'
    toast: boolean
} 

I am using redux-toolkit with slices. In those slices I use createAsyncThunk to fetch my data via axios.

Question 1: What is the best way to read the message from the response and write it to the Redux-Toolkit store to show toasts later? I tried to write a listenerMiddleware and my own middleware. Both variants are doing nearly the same I think. But whats the best way to do it?

Question 2: For reading the message in the middleware I have to return the messages in every createAsyncThunk function in all slices (see code below). Is there a nicer way to read the messages and dispatch the action which stores the message in the store?

export const fetchAllTodos = createAsyncThunk('todo/fetchAll', async () => {
    const response = await axiosInstance.get('/todos/')
    const normalized = normalize<
        schema.Array<Todo>,
        {
            aim: Record<string, Todo>
        }
    >(response.data.data, Schemas.Todos)

    return { entities: normalized.entities, message: response.data.message }
})
0

There are 0 best solutions below