0

I have this code in JSX:

<script type="text/babel">
  function Rows(){
    const [isLoaded, setIsLoaded] = React.useState(false);
    const [items, setItems] = React.useState([]);

    React.useEffect(()=>{

      $.ajax(
      {
        url:"http://localhost:8080/api/manage/products/all",
        success:function(data){
          setItems(data);
          console.log(data);
          console.log(items);
          setIsLoaded(true);
        }
      });

    },[]);

      return(
        <React.Fragment>
          {items.map((o)=>{
            <tr>
                <th scope="row">{o.id}</th>
                <td>{o.prdname}</td>
              </tr>
          })}
        </React.Fragment>
      );
  }

  ReactDOM.render(<Rows />,document.getElementById("clientBody"));

</script>

I get the data array output in the console as expected but for the items I get an empty array. What is the problem and how do I solve it? I want to use hooks and jQuery for that.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
  • sorry it does not. i took a look at it before i asked – AmineBinOthman Dec 31 '21 at 15:51
  • 2
    Are you certain the proposed duplicate does not answer your question? It appears to be the same issue, with the same underlying cause (from what I see), with a proper answer. If the proposed duplicate truly does not answer your question, can you specify in what way you believe your situation differs, to better enable the community to provide you with help? Thanks, and happy coding! – Alexander Nied Dec 31 '21 at 15:55
  • Are you getting any errors in the console as well? – Siddharth Seth Dec 31 '21 at 15:55
  • 2
    The linked answer should explain that `setItems(data)` does not update `items` in the current context. `items` is updated on the next render, therefore `console.log(items)` directly after `setItems(data)` displays the old `items`. If you want to use the new value you could just reference `data` instead of `items`. If you rather have an updated label you could introduce a new local variable `const items = data`, then `setItems(items)` to update the state on the next render. You can then freely use `items` (within the callback). – 3limin4t0r Dec 31 '21 at 15:56
  • no error exept a warning indicating that i am using the in-browser babel – AmineBinOthman Dec 31 '21 at 15:56
  • please use axios calls or fetch .. i never understood jquery in react .. it defeats its purpose – Shoyeb Memon Dec 31 '21 at 15:56

0 Answers0