D
D
DimaSBB2020-10-22 12:33:57
React
DimaSBB, 2020-10-22 12:33:57

With a post request, the data is displayed only after the page is reloaded (React). How to fix?

In general, I make a post request to add (the addTask function). There is a function (getAllTasks) that makes a get request to display data on the same page. The problem is that the data appears only after the page is refreshed. I tried to do tracking for changing tasks in useEffect, but then an endless chain of get requests is launched. In general, how to fix it?

The code:

const [title, setTitle] = useState("");
    const [tasks, setTasks] = useState(null);
    const allTextLang = LangService.key().allText;
    const maxSize = 50;

    const handleChangeField = (event) => {
        const value = event.target.value;
        setTitle(prevValue => InputValidator(prevValue, value, maxSize));
    };

    useEffect(() => {
        getAllTasks(); 
    }, []);

    const getAllTasks = async () => {
        const responce = await API.get("/tasks");       
        setTasks(responce.data);
    };

    const addTask = (event) => {
        event.preventDefault();

        API.post("/tasks", {
            title: title
        });
    };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim, 2020-10-22
@DimaSBB

Well, you have 2 options here.
1) After addTask, call getAllTasks (2 requests, but the most up-to-date data)
2) in addTask, do not only post to the server, but also update the state. (better, of course, divided into 2 functions, so as not to violate the principle of single responsibility)
that is:

const addTask = async (event) => {
        event.preventDefault();

        await API.post("/tasks", {
            title: title
        });

        setTasks([...tasks, { title: title }])
    };

However, here it is worth considering that if the Post request fails, and you update the state, then the data will not be relevant for the user. Thus, if yours API.postreturns a promise, then it is worth updating the state in .then (). Well, or through await
Next, already look at the situation that suits you best.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question