Home > front end >  React.js does not update the UI if I useState
React.js does not update the UI if I useState

Time:09-06

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.

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?

CodePudding user response:

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.

  • Related