Я создал настраиваемую ловушку для выполнения асинхронного c вызова API-интерфейса rest, который возвращает массив объектов. У меня есть два метода asyn c. Первый метод возвращает список объектов. При успешном вызове отдыха массив состояний [dataEntry] обновляется, но при втором вызове, когда почтовый запрос возвращает единственный объект. Когда я пытаюсь добавить только что возвращенный объект в массив состояний [dataEntry], я не могу увидеть новый объект, добавленный в массив.
import { useState, useContext } from 'react';
import restApi from '../api/restApi';
import { Context as AuthContext } from '../context/AuthContext';
export default () => {
const { state } = useContext(AuthContext);
const [lastPage, setLastPage] = useState(true);
const [nextPageNumber, setNextPageNumber] = useState(0);
const [dataEntry, setDataEntry] = useState([]);
const [errorMessage, setErrorMessage] = useState(null);
const [dataUpdate, setDataUpdate] = useState(false);
const getAllData = async (pageNumber, pageSize) => {
try {
restApi.get('/data/list', {
headers: {
Authorization: 'Bearer ' + state.tokenData,
'Content-Type': 'application/json'
}
}).then(response => {
console.log(response.data.result);
setLastPage(response.data.lastPage);
setNextPageNumber(response.data.nextPageNumber);
setDataEntry([...response.data.result]);
setDataUpdate(true);
})
} catch (error) {
console.log(error.response.data);
}
}
const createData = async ({ dataName }) => {
try {
console.log('creating data ' + dataName);
restApi.post(
"/data", {
dataName
}, {
headers: {
Authorization: 'Bearer ' + state.tokenData,
'Content-Type': 'application/json'
}
}).then(response => {
console.log(response.data);
console.log(dataEntry.length)
setDataEntry([...dataEntry, response.data]);
console.log(dataEntry.length)
setDataUpdate(true);
})
} catch (error) {
console.log(error.response.data);
}
}
return [getAllData, createData, dataEntry, lastPage, nextPageNumber, dataUpdate];
}