Need for thunks if I use Redux Toolkit and RTK-Query?
Asked Answered
A

1

6

I am using Redux Toolkit (RTK) and Redux Toolkit Query (RTK-Query).

Is it best practice, necessary, or advised in any scenario to still use thunks, or should I move all logic into components? (like in handleLogin() below)

const Login = () => {

    const dispatch = useDispatch()
    const [formState, setFormState] = useState({ name: '', password: '' })
    const [login, { isLoading }] = useLoginMutation()
    const { push } = useHistory()

    const handleLogin = async () => {
        try {
            const user = await login(formState).unwrap()
            dispatch(setCredentials(user));
        } catch (e) {
            console.error(e)
        }
    }


    return (
        <div>
            <input type="text" name="name" placeholder="name" />
            <input type="password" name="password" placeholder="password" />
            <button onClick={handleLogin}>Login {isLoading ? '...' : ''}</button>
        </div>
    )
}

export default Login
Aylward answered 9/9, 2021 at 14:9 Comment(0)
M
16

As we specifically say in the RTK Query docs

RTK Query is a powerful data fetching and caching tool. It is designed to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.

You're still welcome to write additional logic with other approaches if you'd like, but one of the goals for RTKQ is that the API definitions can completely replace the need to write any thunks or other async logic by hand.

Munster answered 9/9, 2021 at 16:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.