S
S
saqo_tadevosyan2020-07-11 13:36:32
JavaScript
saqo_tadevosyan, 2020-07-11 13:36:32

The state does not change, what's wrong?

It is necessary that when the page is loaded, it receives data from the server and saves it to the state, the problem is that the state does not change. Here is a piece of code.
const { loading, error, request } = useHttp();
const [items, setItems] = useState([]);

let getItems = () => {
try {
const data = request("/api/item", "GET").then((answer) => {
setItems(JSON.parse(answer));

});

return JSON parse(data);
} catch (error) {
console.log(error.message);
}
};

useEffect(() => {
getItems();
new WOW.WOW().init();
return () => {};
}, []);

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dima Polos, 2020-07-11
@dimovich85

You are going to synchronously take the data and change the state before the request is completed. For the same reason, try catch won't work either.

S
saqo_tadevosyan, 2020-07-11
@saqo_tadevosyan

Even if you delete the request to the server and write setItem("test") in useeffect, the state still does not change.

N
NeverSmileMan, 2020-07-12
@NeverSmileMan

lay out the complete component with the useHttp() hook, and you will be happy

A
alex kapustsin, 2020-07-12
@holysheepcoder

I support. Lay out the normal component as it is.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question