Home > other >  State is not Setting
State is not Setting

Time:05-07

I am trying to store the result of my backend, which is a list of inventories, sent from my backend powered by Microsoft .Net 6 Web API.

But I can't figure out why, when I try to "set" the response which is an array to my inventory_state React doesn't save it.

Am I thinking I'm doing the axios service wrong?

Here:

SetInventory_state({
  ...inventory_state,
  inventories: response.data,
});

Axios Service

// frontend\src\services\http-server.js
import axios from "axios";

const http = axios.create({
  baseURL: "http://192.168.1.10:1010/api/",
  headers: {
    "Content-type": "application/json",
  },
});
export default http;

DataServiceInventory

// frontend\src\services\Data\DataServiceInventory.js
import http from "../http-server";

class DataServiceInventory {
  AllList() {
    return http.get("/inventory/list/");
  }
}
export default new DataServiceInventory();

Page List

// frontend\src\pages\PageInventoryIndex.js

const PageInventoryIndex = function () {
  const [inventory_state, SetInventory_state] = useState({
    inventories: null,
    error: null,
    loading: true,
  });
  const { error, loading, inventories } = inventory_state;

  async function getData() {
    try {
      await DataServiceInventory.AllList().then((response) => {
        console.log(response);
        SetInventory_state({
          ...inventory_state,
          inventories: response.data,
        });
      });
    } catch (err) {
      SetInventory_state({
        ...inventory_state,
        error: err.message,
      });
    } finally {
      SetInventory_state({
        ...inventory_state,
        loading: false,
      });
    }
  }

  useEffect(function () {
    getData();
  }, []);
  

  return (
    <>
      <Console stateName={inventory_state} />
      <Content MaxWidth="800px">
        <ContentHead>
          <IconTitle icon="fluent:clipboard-task-list-rtl-24-regular" />
          <h1>Lista de inventarios</h1>
        </ContentHead>

        <ContentBody>
          {loading && <div>Cargando...</div>}
          {error && (
            <div>{`Hay un problema al obtener los datos - ${error}`}</div>
          )}

          {inventories ? (
            <table id="customers">
              <thead>
                <tr>
                  <th>N#</th>
                  <th>Nombre del Inventario</th>
                  <th>Ubicación</th>
                  <th>Estado</th>
                  <th>Acción</th>
                </tr>
              </thead>
              <tbody>
                {inventories.map((item, index) => (
                  <tr key={index}>
                    <td>{item.inventory_id}</td>
                    <td>{item.name}</td>
                    <td>{item.location}</td>
                    {item.status ? (
                      <td>
                        <span className="badge bg-success">
                          Abierto
                        </span>
                      </td>
                    ) : (
                      <td>
                        <span className="badge bg-secondary">
                          Cerrado
                        </span>
                      </td>
                    )}

                    <td>
                      <Link
                        to={`/dashboard/inventory/${item.inventory_id}/editar/`}
                      >
                        Ver
                      </Link>
                      |
                      <Link
                        to={`/dashboard/inventory/${item.inventory_id}/editar/`}
                      >
                        Editar
                      </Link>
                      |
                      <Link
                        to={`/dashboard/inventory/${item.inventory_id}/cerrar/`}
                      >
                        Cerrar
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : null}
        </ContentBody>
      </Content>
    </>
  );
};
export default PageInventoryIndex;

enter image description here enter image description here

CodePudding user response:

As far as I see your finally block makes a second SetInventory_state invocation which, as far as I know, "overrides" the first one which puts all the correct values into the state. Within the finally block, ...inventory_state is used, which is still the old value from before the first SetInventory_state invocation from the API response.

  • Related