简体   繁体   中英

Using react + hooks, how can i call/use "navigate()" after a async redux dispatch properly?

When using "await" on "dispatch(saveItem(item))" it's not supposed to have any effct,
meanwhile if i don't use the "await" both functions will run in the same time resulting a saved item but not a component rerender.

Although the state changes in the redux store the view doesn't, whilst using the await actually waits for the dispatch to complete and then runs the navigation.

My main question is how to properly navigate after a redux dispatch?

import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate, useParams } from 'react-router-dom';
import { useForm } from '../hooks/useForm';
import { getById } from '../services/itemService';
import { saveItem } from '../store/actions/itemActions';

export function ItemEdit() {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const [item, handleChange, setItem] = useForm(null);
    const itemId = useParams().id;

    useEffect(async () => {
        await loadItem();
    }, []);

    const loadItem = async () => {
        try {
            const item = await getById(itemId)
            setItem(item);
        } catch(err) {
            setErrMsg(err.name + ': ' + err.message);
        }
    };

    const onSaveItem = async (ev) => {
        ev.preventDefault();
        await dispatch(saveItem(item));
        navigate('/item')
    }

    return (
        <form onSubmit={onSaveItem}>
            <button>Save</button>
        </form>
    );
}

You can try it this way:

dispatch(saveItem(item))
.unwrap()
.then(() => navigate('/item'))
.catch(error => 'handle error')

It works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM