Answer the question
In order to leave comments, you need to log in
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
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 }])
};
API.post
returns a promise, then it is worth updating the state in .then (). Well, or through await
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question