Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React.js does not update the UI if I useState

I have a React.js app. Here is extract of the code:

const list = JsonData.map(x => Oppty(x)); // JsonData is just an array I have
...
return (
<Table>
...
<tbody>{list}</tbody>
...
</Table>
)

we render a table with say 7 cols. the first 5 cols define inputs, the last 2 cols define output when we call an API. Each row of the table is a Oppty.

Oppty is another React.FunctionComponent. It makes AJAX calls in a useEffect and updates its state (columns 6 and 7) in the callback. This causes the last 2 columns to fill in with appropriate values. This code works.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But when I change it to:

const [list, setList] = useState(JsonData.map(x => Oppty(x)));

The table renders and I see ajax calls being emitted but the last 2 columns do not update now. Why is that so and how can I fix this?

>Solution :

You’re… using React wrong.

  1. Even if a function component is a function, it’s a very different thing to just call it like you’re doing (Oppty(x)) and to return it as an element (<Oppty {...x} /> would be equivalent, to spread the object x into props). E.g. hooks won’t necessarily work correctly if you call a component as a function (since there is no component boundary).
  2. Don’t put JSX elements or components of any sort in state. Just map your state into elements as you’re rendering.

All in all:

return (
  <Table>
    <tbody>{JsonData.map((x, i) => <Oppty {...x} key={i} /></tbody>
  </Table>
);

If your xes have an unique key of some sort (e.g. an id) use that instead of i for a key.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading