M
M
mletov2021-06-05 17:01:18
React
mletov, 2021-06-05 17:01:18

How to update a component with useState in an ajax callback?

The question for experienced React developers should be pretty simple, but Google shows me everything around the bush.

1) There are 2 components: parent and child. Both components are functional.
2) In the parent there is a button by which
- an ajax request is sent
- in the ajax request callback, the value that arrived from the server is written to the dataSource variable via useState.
- the same dataSource variable is used as an input parameter for the child component and displayed inside it via props.

Naturally, I would like the component to be updated after pressing the button and receiving the value from the server.
But it is updated only after the second click on the button and with the previous value.

A similar component with a synchronous change in input parameters is updated without problems.

I use axios for the request, but I don't think it matters.

I read it, they write that this happens because useState is asynchronous, they recommend using componentWillReceiveProps (), but I have all functional components. Tried analog componentWillReceiveProps for useEffect, something doesn't work.

Please, tell me how to properly update the component in the callback, maybe there is a good example.

https://codepen.io/mletov/pen/QWpxRRL

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xenonhammer, 2021-06-06
@xenonhammer

In the child component, in useeffect, in its dependency, you need to add the prop that comes in and specify the effect that should be implemented

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question